zen
zen

Reputation: 1165

Break out of the each method in Symfony's DomCrawler

I am trying to filter through the specific element and then once the text is found, I want to record the position and break out of the each method. But I cannot break out of it I get the PHP error Cannot break/continue 2 levels

Here's the current code I'm working with:

$crawler->filter('#title')->each(function ($node) use ($new_text, $new_place, $place, $number) {

    // If number is found, record its place
    if (strpos($node->text(), $number) !== false) {
        $new_place = $place;
        $new_text = $node->text();
        break;
    }

    $place++;
});

Upvotes: 2

Views: 1648

Answers (1)

Shaun Bramley
Shaun Bramley

Reputation: 2047

Issue #1 - you are attempting to break from within an if-statement.

Issue #2 - your anonymous function does not actually return any values.

The anonymous function receives the node (as a Crawler) and the position as arguments. The result is an array of values returned by the anonymous function calls.

from Symfony DomCrawler Documentation

Edit: If you are using this to search for the nth element from within the list, you will want to switch to using xpath.

Upvotes: 1

Related Questions