chexyalani
chexyalani

Reputation: 11

PHP - DOMDocument : Getting the id of an element

Ok so, how would I get the paragraph element from the id 'something' from a DOMDocument?

Here is my code

    <?php
      $code="<html> <p id='something'>Hi</p> </html>";
      $dom=new DOMDocument;
      $dom->loadHTML($code);
    ?>

Thanks for the help.

Upvotes: 0

Views: 51

Answers (2)

splash58
splash58

Reputation: 26153

One method is using Xpath

$code="<html> <p id='something'>Hi</p> </html>";
$dom=new DOMDocument;
$dom->loadHTML($code);
$xpath = new DomXpath($dom);
$p = $xpath->query('//p[@id="something"]');
// $p - element needed
echo $p->item(0)->nodeValue;

Upvotes: 0

mega6382
mega6382

Reputation: 9396

By using the getElementById method, like:

$code="<html> <p id='something'>Hi</p> </html>";
$dom=new DOMDocument;
$dom->loadHTML($code);

var_dump($dom->getElementById('something')->nodeValue);

Upvotes: 1

Related Questions