2014-04-05 82 views
0

HTML文字與DOMXPath PHP搜索

<td class="one"> 
    <div> 
    <b> 
     <span>item</span> 
    </b> 
    <div> 
     <c>text</c> 
    </div> 
    </div> 
</td> 


你如何選擇,並通過搜索文本呼應項目

我在PHP中的xpath行遇到困難。

$c = $xpath->query("*/c"); 


PHP

<?php 
$keyword = "String"; 
$search = strtolower($keyword); 

$target_url = "http://www.example.com/"; 

//USER AGENT 
//$userAgent = 'spider'; 
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; 

$ch = curl_init(); 
$options = array(CURLOPT_USERAGENT => $userAgent, 
       CURLOPT_URL    => $target_url, 
       CURLOPT_HEADER   => false, 
       CURLOPT_FAILONERROR  => true, 
       CURLOPT_FOLLOWLOCATION => true, 
       CURLOPT_AUTOREFERER  => true, 
       CURLOPT_RETURNTRANSFER => true, 
       CURLOPT_TIMEOUT   => 20 
       ); 

curl_setopt_array($ch, $options); 
$html= curl_exec($ch); 

if (!$html) 
{ 
    echo "ERROR NUMBER: ".curl_errno($ch); 
    echo "ERROR: ".curl_error($ch); 
    exit; 
} 
curl_close($ch); 


$dom = new DOMDocument(); 
@$dom->loadHTML($html); 
$xpath = new DOMXPath($dom); 
$c = $xpath->query("*/c"); 


foreach($c as $a) { 
    $text = $a->nodeValue; 
    echo($text . '<br />'); 
} 


//echo '<pre>'; 
//print_r($c); 
//echo '</pre>';  
?> 

回答