1

Here is part of my code:

$heading_text = '';
$heading_nodes = $crawler->filter($heading_selector);
if(count($heading_nodes->siblings()) > 0) {
   $heading_text = str_replace('Something', 'Else', htmlentities($heading_nodes->eq(0)->text()));
}

I know that some of the pages I am crawling will not have any element with the $heading_selector. However, that's why I was relying on siblings() to calculate the number of headings and proceed if the value was more than 0.

However, I still got the same error Fatal error: Uncaught InvalidArgumentException: The current node list is empty.. The error was caused by $heading_nodes->siblings().

So, if I cannot use count with siblings() to check if a DOM element exists without throwing an error, what else can I do?

I am using the Symfony DOM crawler: https://symfony.com/doc/current/components/dom_crawler.html.

Thanks.

Real Noob
  • 1,369
  • 2
  • 15
  • 29
  • 1
    Having siblings doesn't mean these siblings also satisfy your selector. You're still trying to `->eq(0)` on something that is empty. (As a note, I don't know about this DOM crawler lib so I'm pretty much guessing, but this seems like a pretty straightforward/common API.) You probably just want to test `if ($heading_nodes->count() > 0)`. – Jeto Dec 06 '19 at 12:14
  • Thanks @Jeto. :) I don't fully understand this part "Having siblings doesn't mean these siblings also satisfy your selector.". Could you please give me an example? – Real Noob Dec 06 '19 at 12:18
  • 1
    A sibling is just an element that is at the same level. So a heading element could be at the same level as a div, or a paragraph, etc., or even a different heading (that wasn't matched by your initial filter). – Jeto Dec 06 '19 at 12:19
  • Thanks @Jeto. :) The `count()` method is not mentioned in the documentation of the library. So, I don't know if it would work. – Real Noob Dec 06 '19 at 12:21
  • 1
    https://github.com/symfony/symfony/blob/5.0/src/Symfony/Component/DomCrawler/Crawler.php#L1080 ? (since `filter` seems to return a `Crawler` instance). – Jeto Dec 06 '19 at 12:22
  • Haha. Thanks @jeto. :) I should have also looked at the source code. – Real Noob Dec 06 '19 at 12:24

0 Answers0