2

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++;
});
zen
  • 1,115
  • 3
  • 28
  • 54
  • 1
    You can try use `return $new_text;` or refactoring your code and write this in variable `$cr = $crawler->filter('#blablabla')` and check each in foreach instruction `foreach($cr as $_cr) { }` – Naumov Feb 14 '16 at 21:12
  • Thanks @Naumov. I guess the `foreach` will work. I'm not sure if there's any better way of doing it, but this should work for me. – zen Feb 14 '16 at 21:18

1 Answers1

1

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.

Shaun Bramley
  • 1,989
  • 11
  • 16