MobileCushion
MobileCushion

Reputation: 7095

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.

Upvotes: 5

Views: 3008

Answers (1)

Kevin
Kevin

Reputation: 41903

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/>';
}

Upvotes: 6

Related Questions