2010-08-10 129 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"; 
}