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 Symfony\Component\DomCrawler\Crawler;

$html = <<<EOD
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>

// 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: