PHP搜索带有特定单词的网站

问题描述 投票:1回答:3

我正在尝试用特定的字词监视网站的新产品页面。我已经有一个基本脚本,可以使用file_get_contents();搜索单个单词,但这无效。

查看它们在<td><table>标记中的代码

[如何获取PHP以无论其顺序如何搜索单词并获取它们所处的声明?例如

$searchTerm = "Orange Boots";

来自:

<table>
   <td>Boots (RED)</td>
</table>
<table>
   <td>boots (ORANGE)</td>
</table>
<table>
   <td>Shirt (GREEN)</td>
</table>

返回比赛。

抱歉,不清楚,但希望您能理解

php search
3个回答
2
投票

您可以这样做

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

并且只需为类红色编写css,就像您想显示比color:red;的红色,并为休息做同样的事情

但是更好的方法是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 />";
} 
© www.soinside.com 2019 - 2024. All rights reserved.