How to find sibling HTML nodes using DOM Crawler and PHP?

You can find sibling HTML nodes using
DOM Crawler
and PHP by utilizing the
siblings method
of a Crawler object. Here is some sample code that extracts the first p node, then extracts its siblings using the siblings method, and finally loops over these sibling nodes and prints their text content:

use SymfonyComponentDomCrawlerCrawler;

$html = <<<EOD
  

This is the first paragraph.

This is the second paragraph.

This is the third paragraph.

EOD; // Load the HTML document $crawler = new Crawler($html); // Find the first p element $pElement = $crawler->filter('p')->first(); // Find all sibling elements of the p element $siblings = $pElement->siblings(); // Loop over the siblings and print their text content foreach ($siblings as $sibling) { echo $sibling->textContent . PHP_EOL; } // Output: // This is the second paragraph. // This is the third paragraph.

Related DOM Crawler web scraping questions:

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *