Using PHP to get DOM Element

getElementsByTagName returns you a list of elements, so first you need to loop through the elements, then through their attributes.

$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
    foreach ($div->attributes as $attr) {
      $name = $attr->nodeName;
      $value = $attr->nodeValue;
      echo "Attribute '$name' :: '$value'<br />";
    }
}

In your case, you said you needed a specific ID. Those are supposed to be unique, so to do that, you can use (note getElementById might not work unless you call $dom->validate() first):

$div = $dom->getElementById('divID');

Then to get your attribute:

$attr = $div->getAttribute('customAttr');

EDIT: $dom->loadHTML just reads the contents of the file, it doesn’t execute them. index.php won’t be ran this way. You might have to do something like:

$dom->loadHTML(file_get_contents('http://localhost/index.php'))

Leave a Comment