Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get id of HTML elements

In PHP, I want to parse a HTML page and obtain the ids of certain elements. I am able to obtain all the elements, but unable to obtain the ids.

$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 also obtain the id of the element?

Thank you.

like image 337
MobileCushion Avatar asked Oct 01 '14 14:10

MobileCushion


1 Answers

If you want the id attribute values, then 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/>';
}
like image 179
Kevin Avatar answered Oct 01 '22 17:10

Kevin