不知道我是否正確理解這個問題,但第二個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"
}
}
正如你可以看到,返回的節點列表中只包含A和HREF包含元素富(我明白你是在找什麼)。它包含整個元素,因爲XPath轉換爲獲取所有包含foo的href屬性的元素。然後,您將與
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"
輸出的URL現在3210
是的,但搜索'needle'會返回* $ node-> nodeValue(); *中的文本部分,而不是所需的* http://example.com?param = needle * ...? – MattW 2010-03-06 12:33:39