XPath 获取 PHP 中的属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8027323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:48:03  来源:igfitidea点击:

XPath get attribute value in PHP

phpxpath

提问by jerrymouse

Possible Duplicate:
How to extract a node attribute from XML using PHP's DOM Parser

可能的重复:
如何使用 PHP 的 DOM 解析器从 XML 中提取节点属性

How do I extract an HTML tag value?

如何提取 HTML 标记值?

HTML:

HTML:

<input type="hidden" name="text1" id="text1" value="need to get this">

PHP:

PHP:

$homepage = file_get_contents('http://www.example.com');
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($homepage);
$xpath = new DOMXpath($doc);
$filtered = $xpath->query("//input[@name='text1']");

How do I get valueto be "need to get this"?

我如何value成为“需要得到这个”

Update:

更新:

I got it working and hope it will help others too. After above code I got the value by:

我让它工作了,希望它也能帮助其他人。在上面的代码之后,我通过以下方式获得了价值:

echo $filtered->item(0)->getAttribute('value');

回答by Martin Honnen

XPath can do the job of getting the value attribute with $xpath->query("//input[@name='text1']/@value");. Then you can iterate over the node list of attribute nodes and access the $valueproperty of each attribute node.

XPath 可以完成获取 value 属性的工作$xpath->query("//input[@name='text1']/@value");。然后您可以遍历属性节点的节点列表并访问$value每个属性节点的属性。

回答by TROODON

Look at this DOM method: http://www.php.net/manual/en/domelement.getattribute.php

看看这个DOM方法:http: //www.php.net/manual/en/domelement.getattribute.php

var array_result = array();
foreach (filtered as $key => $value){
    $array_result[] = $value->getAttribute('ID'); 
}

回答by fearphage

I'm not familiar with the PHP syntax for this, but to select the value attribute you would use the following xpath:

我不熟悉 PHP 语法,但要选择 value 属性,您将使用以下 xpath:

//input[@name='text1']/@value

However xpath doesn't return strings, it returns nodes. You want the nodeValueof the node, so if PHP follows convention, that code would be:

但是 xpath 不返回字符串,它返回节点。您需要nodeValue节点的 ,因此如果 PHP 遵循约定,则该代码将是:

 $xpath->query("//input[@name='text1']/@value")->item(0).nodeValue;

For learning purposes, keep in mind you always check the nodeValueproperty. So if you wanted the name of the same element, you'd use:

出于学习目的,请记住您始终检查该nodeValue属性。因此,如果您想要相同元素的名称,则可以使用:

 $xpath->query("//input[@name]/@name")->item(0).nodeValue;

You'd probably like to make sure the query returns a non-null value before querying the nodeValueproperty as well.

在查询nodeValue属性之前,您可能还想确保查询返回非空值。