Gorna-Bania Gorna-Bania - 15 days ago 7
HTML Question

PHP: Getting DOM elements by classname

I have the following:

<div id="content">
<div class="content-top">bla</div>
<div class="inner text-inner">
bla bla bla
</div>
</div>


and the PHP:

$page = file_get_contents('http://www.example.com/test');
@$doc = new DOMDocument();
@$doc->loadHTML($page);
$node = $doc->getElementById('content');


How can I modify
$node = $doc->getElementById('content');
so i can target
<div class="inner text-inner">
?

Answer

You can use XPath to easily achieve it.

$page = file_get_contents('http://www.example.com/test');
@$doc = new DOMDocument();
@$doc->loadHTML($page);   

$xpath = new DomXPath($doc);

$nodeList = $xpath->query("//div[@class='inner text-inner']");
$node = $nodeList->item(0);

// To check the result:
echo "<p>" . $node->nodeValue . "</p>";

This will output:

bla bla bla
Comments