2010-08-10 136 views
0

以下PHP代碼使用cURL,XPath並顯示某個頁面上的所有鏈接($ target_url)。cURL和XPath顯示href錨文本?

**我想要做的是弄清楚如何在我提供網站價值時只顯示給定頁面上的錨文本(鏈接文字在href中)。

比如......我想搜索「randomwebsite.com」,看看是否有與我target_url鏈接(例如:ebay.com)和顯示公正「的拍賣網站」的錨文本

http://www.ebay.com'>拍賣網站


<?php 


$target_url = "http://www.ebay.com"; 
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; 

// make the cURL request to $target_url 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); 
curl_setopt($ch, CURLOPT_URL,$target_url); 
curl_setopt($ch, CURLOPT_FAILONERROR, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true); 
curl_setopt($ch, CURLOPT_TIMEOUT, 10); 
$html= curl_exec($ch); 
if (!$html) { 
    echo "<br />cURL error number:" .curl_errno($ch); 
    echo "<br />cURL error:" . curl_error($ch); 
    exit; 
} 

// parse the html into a DOMDocument 
$dom = new DOMDocument(); 
@$dom->loadHTML($html); 

// grab all the on the page 
$xpath = new DOMXPath($dom); 
$hrefs = $xpath->query('/html/body//a'); 

for ($i = 0; $i < $hrefs->length; $i++) { 
    $href = $hrefs->item($i); 
    $url = $href->getAttribute('href'); 
    echo "<br />Link: $url"; 
} 

?> 
+0

你的問題在哪裏?我沒看到一個。 – 2010-08-11 02:37:52

回答

1

你會得到你的例子循環內與$href->nodeValue文本。如果它是一個圖像標籤或者其他類似的東西,這並不能真正解釋你想要做什麼,但是我認爲這就是你特別要求的。

+0

完美的是,對於我這個製作精良的問題,你仍然找到了答案!謝謝! – semjuice 2010-08-23 20:36:19

+0

謝謝。一直在尋找嘗試。 innerHTML,文本等thx prodigitalson – Email 2011-04-24 23:51:23

0

不知道我是否明白你要求的內容......但也許這是你想要實現的內容?

$url_matches = array('www.ebay.com' => 'Auction Site', 
        'www.google.com' =>'Search Engine' 
       ); 

for ($i = 0; $i < $hrefs->length; $i++) { 
    $href = $hrefs->item($i); 
    $url = $href->getAttribute('href'); 
    if (in_array($url, $url_matches)) { 
     $url = $url_matches[$url]; 
    }  
    echo "<br />Link: $url"; 
}