不确定我是否正确理解了这个问题,但第二个 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 转换为获取所有具有包含 foo 的 href 属性的 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"
}
}
}
但您现在可以通过
输出网址
echo $list[0] // gives "http://example.com/page?foo=bar"