2010-08-10 6 views
0

Le code PHP suivant utilise cURL, XPath et affiche tous les liens sur une certaine page ($ target_url).cURL & XPath pour afficher le texte d'ancrage href?

** Ce que j'essaie de faire est de comprendre comment afficher uniquement le texte d'ancrage (les mots liés dans un href) sur une page donnée lorsque je fournis la valeur du site.

Par exemple ... Je veux rechercher « randomwebsite.com » pour voir s'il y a un lien avec mon target_url (ex. Ebay.com) et l'affichage juste le texte d'ancre « site d'enchères »

http://www.ebay.com '> site d'enchères


<?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

Où est votre question? Je n'en vois pas. –

Répondre

1

Vous obtiendrez le texte avec $href->nodeValue dans votre boucle d'exemple. Cela ne tient pas vraiment compte de ce que vous pourriez vouloir faire si c'est un tag d'image ou autre, mais je pense que c'est ce que vous demandiez spécifiquement.

+0

Parfait, pour ma question mal conçue, vous avez toujours trouvé la réponse! Merci! – semjuice

+0

merci. J'ai cherché à essayer aussi. innerHTML, texte, etc. thx prodigitalson – Email

0

Je ne sais pas si j'ai compris ce que vous demandiez ... mais c'est peut-être ce que vous voulez mettre en œuvre?

$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"; 
} 
Questions connexes