简体   繁体   中英

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.

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM