2012-12-31 50 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 />"; 
}