XPath get attribute value in PHP

XPath can do the job of getting the value attribute with $xpath->query("//input[@name='text1']/@value");. Then you can iterate over the node list of attribute nodes and access the $value property of each attribute node.


I'm not familiar with the PHP syntax for this, but to select the value attribute you would use the following xpath:

//input[@name='text1']/@value

However xpath doesn't return strings, it returns nodes. You want the nodeValue of the node, so if PHP follows convention, that code would be:

 $xpath->query("//input[@name='text1']/@value")->item(0).nodeValue;

For learning purposes, keep in mind you always check the nodeValue property. So if you wanted the name of the same element, you'd use:

 $xpath->query("//input[@name]/@name")->item(0).nodeValue;

You'd probably like to make sure the query returns a non-null value before querying the nodeValue property as well.


Look at this DOM method: http://www.php.net/manual/en/domelement.getattribute.php

$array_result = array();
foreach (filtered as $key => $value) {
    $array_result[] = $value->getAttribute('ID'); 
}

Tags:

Php

Xpath