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

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 
  • 写回答

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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求解答(matlab)
  • ¥30 ffmpeg库使用过程中遇到的问题
  • ¥15 pyqt5 中python如何通过Qtwebchannel主动发消息给web前端
  • ¥15 关于HTML中title获取xml内容的问题
  • ¥15 fanuc机器人PRIO083数字信号未复原错误,如何解决?
  • ¥20 如何为现有电路板增加远程控制功能
  • ¥15 C#点击按钮的时候的循环次数就是最后一次,如何是循环第几次的值?
  • ¥15 UE5打包失败,求解决
  • ¥15 请问STM32G431的CANOPEN协议函数怎么写
  • ¥15 graphpad prism 三因素重复测定报错