简体   繁体   English

PHP DOMDocument:从id获取属性值

[英]PHP DOMDocument: Get attribute value from id

I would like to extract the value of the attribute "value" using the id tag. 我想使用id标记提取属性“ value”的值。

My code: 我的代码:

<?php
 $url = 'http://turni.tt-contact.com/Default.aspx';
 $contents = htmlentities(file_get_contents($url));
 echo $contents."\n"; //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. 但是该代码仅返回html代码。

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 

Try this : 尝试这个 :

$data->getAttribute('value'); 

PHP: DomElement->getAttribute 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);

Don't use htmlentities as it will change the document's HTML tags from : <html> to &lt;html&gt; 不要使用htmlentities因为它会将文档的HTML标记从<html>更改为&lt;html&gt; and your document won't be HTML anymore, just a plain text full of &lt; 并且您的文档将不再是HTML,而只是包含&lt;的纯文本&lt; and &gt; &gt; , and so the methods to get nodes won't work. ,因此获取节点的方法将行不通。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM