Extract value of a input hidden DOMXpath php

2.9k views Asked by At

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
2

There are 2 answers

0
Anass On BEST ANSWER

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);
2
Anass On

i find a solution for you using PHP Simple HTML DOM Parser :

don't forget download this library : http://simplehtmldom.sourceforge.net/

include("simple_html_dom.php");
$html=str_get_html('<input type="hidden" id="Lat" name="myMap" value="22.445575, -18.722164">');
$input_val=$html->find('input[type=hidden],[name=myMap]',0)->getAttribute("value");
echo $input_val;

if you want fetch html from url change str_get_html with file_get_html :

$html=file_get_html("http://www.example.com/page");