doushi9856
2017-10-10 14:52
浏览 279
已采纳

PHP DOMDocument:从id获取属性值

I would like to extract the value of the attribute "value" using the id tag.

My code:

<?php
 $url = 'http://turni.tt-contact.com/Default.aspx';
 $contents = htmlentities(file_get_contents($url));
 echo $contents."
"; //html
 $dom = new DOMDocument;
 $dom->validateOnParse = true;
 $dom->loadHTML($contents);
 $dom->preserveWhiteSpace = false;
 $data = $dom->getElementById("__VIEWSTATE");
 echo $data->nodeValue;
?>

I would like the attribute "value" -> "THIS":

   <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="THIS">

but the code returns only the html code.

What do I need to change?

Also by modifying it to:

$xpath = new DOMXpath($dom);
$data = $xpath->query('//input[@id="__VIEWSTATE"]');
$node = $data->item(0);
echo $node->getAttribute('value');

I get this error:

  Fatal error: Call to a member function getAttribute() on null 

图片转代码服务由CSDN问答提供 功能建议

我想使用id标签提取属性“value”的值。

我的代码:

 &lt;?php 
 $ url ='http://turni.tt-contact.com/Default.aspx'; \  n $ contents = htmlentities(file_get_contents($ url)); 
 echo $ contents。“
”;  // html 
 $ dom = new DOMDocument; 
 $ dom-&gt; validateOnParse = true; 
 $ dom-&gt; loadHTML($ contents); 
 $ dom-&gt; preserveWhiteSpace = false; 
 $ data  = $ dom-&gt; getElementById(“__ VIEWSTATE”); 
 echo $ data-&gt; nodeValue; 
?&gt; 
   
 
 

我想要属性 “价值” - &gt; “这个”:

 &lt; input type =“hidden”name =“__ VIEWSTATE”id =“__ VIEWSTATE”value =“THIS”&gt; 
  <  / pre> 
 
 

但代码只返回html代码。

我需要更改什么?

同样由 将其修改为:

  $ xpath = new DOMXpath($ dom); 
 $ data = $ xpath-&gt; query('// input [@id =“__ VIEWSTATE  “]'); 
 $ node = $ data-&gt; item(0); 
echo $ node-&gt; getAttribute('value'); 
   
 
 

我收到此错误:

 致命错误:在null 
   
 上调用成员函数getAttribute()
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongshi4078 2017-10-10 14:55
    已采纳

    Try this :

    $data->getAttribute('value'); 
    

    PHP: DomElement->getAttribute

    $attrs = array();
     for ($i = 0; $i < $data->attributes->length; ++$i){
       $node = $data->attributes->item($i);
       $attrs[$node->nodeName] = $node->nodeValue;
     }
     var_dump($attrs);
    
    点赞 评论
  • douhao7677 2017-10-10 19:27

    Don't use htmlentities as it will change the document's HTML tags from : <html> to &lt;html&gt;and your document won't be HTML anymore, just a plain text full of &lt; and &gt;, and so the methods to get nodes won't work.

    点赞 评论

相关推荐 更多相似问题