2010-03-06 77 views
16

使用PHP Xpath嘗試快速拉取html頁面中的某些鏈接。PHP Xpath:獲取包含針的所有href值

下面將找到的mypage.html所有HREF鏈接: $nodes = $x->query("//a[@href]");

而下面會發現所有的href鏈接,其中描述符合我的針: $nodes = $x->query("//a[contains(@href,'click me')]");

什麼我想實現在href本身上是匹配的,更具體的查找包含特定參數的url。這可能在一個Xpath查詢中,或者我應該開始操縱第一個Xpath查詢的輸出嗎?

+0

是的,但搜索'needle'會返回* $ node-> nodeValue(); *中的文本部分,而不是所需的* http://example.com?param = needle * ...? – MattW 2010-03-06 12:33:39

回答

35

不知道我是否正確理解這個問題,但第二個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
+0

這就是我的意思。使用SimpleXML時,只有我的html文檔失敗。儘管如此,xpath查詢仍然有效,並且在DomXpath中使用它可以提供我想要的內容。謝謝! – MattW 2010-03-06 12:42:22