不确定我是否正确理解问题,但第二个XPath表达式已经实现了您所描述的功能。它不是针对A元素的文本节点进行匹配,而是针对href属性进行匹配:
$html = <<< HTML
<ul>
<li>
<a href="http://example.com/page?foo=bar">Description</a>
</li>
<li>
<a href="http://example.com/page?lang=de">Description</a>
</li>
</ul>
HTML;
$xml = simplexml_load_string($html);
$list = $xml->xpath("//a[contains(@href,'foo')]");
输出:
array(1) {
[0]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(1) {
["href"]=>
string(31) "http://example.com/page?foo=bar"
}
[0]=>
string(11) "Description"
}
}
如您所见,返回的NodeList仅包含href中包含foo的A元素(我理解这正是您要查找的内容)。它包含整个元素,因为XPath翻译为获取所有href属性包含foo的A元素。然后,您可以使用以下方法访问属性:
echo $list[0]['href'] // gives "http://example.com/page?foo=bar"
如果您只想返回属性本身,您需要执行以下操作:
//a[contains(@href,'foo')]/@href
请注意,在 SimpleXml 中,这将返回一个 SimpleXml 元素:
array(1) {
[0]=>
object(SimpleXMLElement)#3 (1) {
["@attributes"]=>
array(1) {
["href"]=>
string(31) "http://example.com/page?foo=bar"
}
}
}
但是现在你可以通过以下方式输出URL:
echo $list[0] // gives "http://example.com/page?foo=bar"