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
XPath get attribute value in PHP
提问by jerrymouse
Possible Duplicate:
How to extract a node attribute from XML using PHP's DOM Parser
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 value
to 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 $value
property 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 nodeValue
of 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 nodeValue
property. 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 nodeValue
property as well.
在查询nodeValue
属性之前,您可能还想确保查询返回非空值。