Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Getting DOM elements by classname

Tags:

html

dom

php

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"> ?

like image 270
Gorna-Bania Avatar asked Nov 19 '16 22:11

Gorna-Bania


People also ask

How do you select an element by class?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

What is getElementsByClassName () used for?

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). When called on the document object, the complete document is searched, including the root node.

What does getElementsByClassName () function return?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.


1 Answers

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
like image 127
nanocv Avatar answered Oct 27 '22 16:10

nanocv