PHP DOM文档 : Get attribute value from id

标签 php dom

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

我的代码:

<?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;
?>

我想要属性“value”->“THIS”:

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

但代码仅返回 html 代码。

我需要改变什么?

还可以将其修改为:

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

我收到此错误:

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

最佳答案

试试这个:

$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);

关于PHP DOM文档 : Get attribute value from id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46669797/

相关文章:

javascript - 在 jQuery 中结合查找/过滤功能,同时定位 DOM 元素

javascript - 使用 document.write 来固定 html

javascript - 使用 jQuery 用元素包裹元素内容的子字符串

javascript - 让每个按钮操作其上方的内容

javascript - 刷新后如何将类添加到页面上选中的单选按钮的父标签

php - Laravel 5.4 迁移 :generate fails with Way\Generators\Filesystem\FileNotFound error

php - UTF-8 中的值在 JSON 中被编码为 NULL

php - Drupal 安装问题。奇怪的错误

php - 如何从 PHP 中的链接中删除跟踪代码

php - 如何在 joomla 安装中设置目录权限