2012-08-02 81 views
2

玩弄xpath表達式試圖學習它。我找到了一段代碼,並對其進行了一些調整。我想要做的是獲取頁面上的每一個鏈接。Xpath表達式獲取href。不只是錨文本

$baseurl = "http://www.example.com"; 
$html = file_get_contents($baseurl); 

$dom = new DOMDocument(); 
@$dom->loadHTML($html); 
$xpath = new DOMXPath($dom); 


$ahrefs = $xpath->query('//a'); 

foreach ($ahrefs as $ahref) { 
    echo $ahref->childNodes->item(0)->nodeValue . "<br />"; 
} 

但現在我抓住錨文本。我想要href部分。也許甚至兩個。我究竟做錯了什麼?

回答

4

爲了讓你有訪問節點的attributes財產

echo $ahref->attributes->getNamedItem("href")->nodeValue . "<br />"; 
1
echo $ahref->getAttribute('href') . "<br />"; 
4

使用在href:

//a/@href 

沒有額外的代碼(除了這個表達式的評價) 是必要的。

+1

這對我有效!通用XPath解決方案,而不是PHP特定的笨拙代碼。 – 2014-04-08 22:14:54

+0

@dhalperi,當然。 XPath是可移植的,並且XPath表達式可以在大多數編程語言不變的情況下使用。 – 2014-04-08 23:50:41