34

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

How do I extract an HTML tag value?

HTML:

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

PHP:

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

How do I get value to be "need to get this"?

Update:

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');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jerrymouse
  • 16,964
  • 16
  • 76
  • 97
  • You will have to loop over your filtered elements `$filtered` via `foreach ($filtered as $element) { ... }`and check the node values / attributes yourself. – Smamatti Nov 06 '11 at 13:37
  • 6
    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 06 '11 at 14:24
  • 4
    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 09 '12 at 22:12
  • To use `evaluate`, see https://stackoverflow.com/a/45010743/287948 – Peter Krauss Jul 10 '17 at 11:27

3 Answers3

40

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.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110
14

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'); 
}
pevik
  • 4,523
  • 3
  • 33
  • 44
TROODON
  • 1,175
  • 1
  • 9
  • 17
9

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.

fearphage
  • 16,808
  • 1
  • 27
  • 33