2012-12-31 36 views
1

我试图用特定的词来监视网站的新产品页面。我已经有一个使用file_get_contents();搜索单个单词的基本脚本,但这不起作用。PHP搜索具体词的网站

的代码看他们在<td>标签内的<table>

如何让PHP来搜索的话,无论什么样的顺序,并得到他们的声明是?例如

$searchTerm = "Orange Boots"; 

来自:

<table> 
    <td>Boots (Red)</td> 
</table> 
<table> 
    <td>boots (ORNAGE)</td> 
</table> 
<table> 
    <td>Shirt (Green)</td> 
</table> 

返回匹配。

很抱歉,如果它的不太清楚,但我希望你明白

+0

大声笑!你为什么不在客户端做呢? Javascript风格,那么如果你想用PHP来处理它,只需要用ajax发送它 – Alex

+4

介绍DOM和Xpath! http://phpmaster.com/php-dom-using-xpath/ – FredTheWebGuy

+0

http://querypath.org Querypath是另一种选择。 – MECU

回答

1

你可以做到这一点像

$newcontent= (str_replace('Boots', '<span class="Red">Boots</span>',$cont)); 

和像你想显示红色比color:red;,做只写类红色CSS休息

同样的事情,但更好的办法将DOM和XPath

1

如果你正在寻找做一个快速和肮脏的搜索通过该HTML块,您可以使用preg_match_all()函数尝试一个简单的正则表达式。例如,你可以尝试:

$html_block = get_file_contents(...); 
$matches_found = preg_match_all('/(orange|boots|shirt)/i', $html_block, $matches); 

$matches_found是1或0,作为指示,如果找到匹配与否。 $matches将根据任何匹配填充。

1

使用卷曲。它比filegetcontents()快得多。这是一个起点:

$target_url="http://www.w3schools.com/htmldom/dom_nodes.asp"; 
// make the cURL request to $target_url 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$target_url); 
curl_setopt($ch, CURLOPT_FAILONERROR, 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) {exit;} 
$dom = new DOMDocument(); 
@$dom->loadHTML($html); 

    $query = "(/html/body//tr)"; //this is where the search takes place 

$xpath = new DOMXPath($dom); 
$result = $xpath->query($query); 

for ($i = 0; $i <$result->length; $i++) { 
    $node = $result->item(0); 
    echo "{$node->nodeName} - {$node->nodeValue}<br />"; 
}