简体   繁体   English

仅获取DOM xPath查询的第一个结果

[英]Getting Only the first result of a DOM xPath query

Let's say I have this code: 假设我有这段代码:

$dom = new DOMDocument();
@$dom->loadHTMLFile('sample.html');
$xp = new DOMXPath($dom);
$result = $xp->query("//input[@id='honey']");

How do I get the content of the attribute value of the first result only, since I'm only expecting one result (without using a foreach loop). 如何仅获取第一个结果的属性value的内容,因为我只期望一个结果(不使用foreach循环)。 I tried var_dump -ing the result but it can't. 我尝试了var_dump -ing结果,但它不能。 I also tried current($result)->getAttribute('value') but not luck. 我也试过current($result)->getAttribute('value')但不是运气。

您可以通过以下方法访问它:

$value = $result->item(0)->attributes()->getNamedItem("value")->nodeValue;

Just evaluate this XPath expression : 只需评估此XPath表达式

(//input[@id='honey'])[1]/@value

This selects the attribute value of the first input element in the XML document, the string value of whose id attribute is "honey" . 这将选择属性value的第一input XML文档中元件,的字符串值,其id属性是"honey"

If you want to get not the value attribute, but its string value, use : 如果您不想获取value属性,而是获取其字符串值,请使用

string((//input[@id='honey'])[1]/@value)

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

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