如何检查文本是否存在于网页上


How to check if text is present on a webpage?

如何检查文本是否存在于使用PHP的网页上,如果是真的执行一些代码?

我的想法是在完成订单后在确认页面上显示一些相关的产品-如果产品的名称出现在页面上,那么加载一些产品。但是我不能检查当前文本

Case 1如果您在变量中准备页面,则在脚本末尾返回它,如

 $response = "<html><body>";
 $response .= "<div>contents text_to_find</div>";
 $response .= "</body></html>";
 echo  $response;

那么你可以用任何字符串搜索函数来搜索字符串

if(strpos($response,"text_to_find") !==false){
    //the page has the text , do what you want
}


第2种情况,如果您不以字符串形式准备页面。你只需回显内容并输出<?php ?>标签外的内容,如

<?php 
   //php stuff
?>
<HTML>
  <body>
<?php 
   echo "<div>contents text_to_find</div>"
?>
  </body>
</HTML>

那么你没有办法捕获你想要的文本,除非你使用输出缓冲


情况3如果你使用输出缓冲-我建议-像

<?php
    ob_start(); 
   //php stuff
?>
<HTML>
  <body>
<?php 
   echo "<div>contents text_to_find</div>"
?>
  </body>
</HTML>

然后你可以随时搜索输出

$response = ob_get_contents()
if(strpos($response,"text_to_find") !==false){
    //the page has the text , do what you want
}

您可能需要像这样buffer您的输出…

<?php
    ob_start();
    // ALL YOUR CODE HERE...
    $output = ob_get_clean();
    // CHECK FOR THE TEXT WITHIN THE $output.
    if(stristr($output, $text)){
      // LOGIC TO SHOW PRODUCTS WITH $text IN IT...
    }
   // FINAL RENDER:
   echo $output;

最快的解决方案是使用php DOM解析器:

$html = file_get_contents('http://domain.com/etc-etc-etc');
$dom = new DOMDocument;
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
$txt = '';
foreach ($divs as $div) {
    $txt .= $div->textContent;
}

这样,变量$txt将保留给定网页的文本内容,只要它被包围在div标签周围,就像通常一样。好运!