How to get the id of HTML elements

In PHP, I want to parse an HTML page and get the identifiers of certain elements. I can get all the elements, but I can not get the identifiers.

$doc = new DOMDocument(); $doc->loadHTML('<html><body><h3 id="h3-elem-id">A</h3></body></html>'); $divs = $doc->getElementsByTagName('h3'); foreach($divs as $n) { (...) } 

Is there a way to get the item id?

Thanks.

+5
source share
1 answer

If you need id attribute values, you need to use getAttribute() :

 $doc = new DOMDocument(); $doc->loadHTML('<html><body><h3 id="h3-elem-id">A</h3></body></html>'); $divs = $doc->getElementsByTagName('h3'); foreach($divs as $n) { echo $n->getAttribute('id') . '<br/>'; } 
+5
source

Source: https://habr.com/ru/post/1203802/


All Articles