Home » Php » XPath get attribute value in PHP

XPath get attribute value in PHP

Posted by: admin April 23, 2020 Leave a comment


Possible Duplicate:
How to extract a node attribute from XML using PHP's DOM Parser

How do I extract an HTML tag value?


<input type="hidden" name="text1" id="text1" value="need to get this">


$homepage = file_get_contents('http://www.example.com');
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$xpath = new DOMXpath($doc);
$filtered = $xpath->query("//input[@name='text1']");

How do I get value to be “need to get this”?


I got it working and hope it will help others too. After above code I got the value by:

echo $filtered->item(0)->getAttribute('value');
How to&Answers:

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.


Look this method of DOM

var array_result = arrray();
foreach (filtered as $key => $value){

    $array_result[] = $value->getAttribute('ID'); 



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


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:


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:


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