Using PHP to get DOM Element Using PHP to get DOM Element php php

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


You won't have access to the HTML if the redirect is from an external server. Let me put it this way: the DOM does not exist at the point you are trying to parse it. What you can do is pass the text to a DOM parser and then manipulate the elements that way. Or the better way would be to add it as another GET variable.

EDIT: Are you also aware that the client can change the HTML and have it pass whatever they want? (Using a tool like Firebug)