Search code examples
phpxpathinputhiddennodevalue

Extract value of a input hidden DOMXpath php


I need take the attribute value using xpath, I tried several times but always get null.

Here is my html code:

<input type="hidden" id="Lat" name="myMap" value="22.445575, -18.722164">

Code in php:

$val= $xpath->query('//input[@type="hidden" and @name="myMap"]/@value' );

$list=array();              

    foreach($val as $v){
       $list[]=$v->nodeValue;
      }

var_dump($list);
$sValue= (string)$val[0];

Notes:

  • I've tried with other xpath in the same url and it works, but not with hidden input
  • I've tried with $v->item(0); or item(0)->nodeValue; and they always produce the same result

Solution

  • this is your code using DOM xpath :

    $html='<input type="hidden" id="Lat" name="myMap" value="22.445575, -18.722164">';
    $doc = new DOMDocument;
    $doc->loadHTML($html);
    $xpath = new DOMXpath($doc);
    $val= $xpath->query('//input[@type="hidden" and @name = "myMap"]/@value' );
    $list=array();              
        foreach($val as $v){
           $list[]=$v->nodeValue;
          }
    var_dump($list);