Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract attribute value of a hidden input element using DOMXPath

Tags:

dom

php

xml

xpath

I have a got piece of HTML code:

<form method="post" action="/">
  <input type="hidden" name="example-name" value="example-value">
  <button type="submit">Submit</button>
</form>

How can I extract value of the hidden input using DOMXPath in PHP? I have tried somethig like this:

//$site - the html code
$doc = new DOMDocument();
$doc->loadHTML($site);
$xpath = new DOMXpath($doc);

$kod = $xpath->query("//input[@name='example-name']");
foreach($kod as $node)
$values[]=$node->nodeValue;
return $values;

But it returns an empty array. Where is the mistake?

like image 793
monthon1 Avatar asked Dec 17 '22 03:12

monthon1


1 Answers

Try this to get the value attribute of the input element with the name attribute example-name

'//input[@name="example-name"]/@value'

Result

Array
(
    [0] => example-value
)

Your XPath didn't select the attribute axis (I think that's what it's called) but the text axis and since input has no text, the value in the array was empty. It did find the element though.

like image 135
Gordon Avatar answered Jan 01 '23 11:01

Gordon