不确定我正确地理解了这个问题,但是第二个XPath表达式已经做了你所描述的内容.它与A元素的文本节点不匹配,但href属性:
$html = <<< HTML
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只包含包含foo的href的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"
}
}
}
但是现在可以输出URL
echo $list[0] // gives "http://example.com/page?foo=bar"