Take the 2-minute tour ×

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

How to 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 to get value "need to get this"


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

echo $filtered->item(0)->getAttribute('value');
share|improve this question
You will have to loop over your filtered elements $filtered via foreach ($filtered as $element) { ... }and check the node values / attributes yourself. –  Smamatti Nov 6 '11 at 13:37
One option is the less-used evaluate() method, which will return the text or an empty string: $xpath->evaluate('string(//input[@name="text1"]/@value)'); –  salathe Nov 6 '11 at 14:24
This isn't really an exact duplicate of the other question. This one is really a cross-environment xpath solution, the other is php specific. –  Factor Mystic Sep 9 '12 at 22:12
add comment

marked as duplicate by Gordon, OZ_, tereško, hakre, Dimitre Novatchev Nov 6 '11 at 17:46


3 Answers

up vote 10 down vote accepted

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.

share|improve this answer
just closevote please. its a duplicate –  Gordon Nov 6 '11 at 13:53
add comment

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

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

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

share|improve this answer
add comment

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 value of the node, so if PHP follows convention, that code would be:


For learning purposes, keep in mind you always check the value 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 value property as well.

share|improve this answer
add comment
