Gorna-Bania
Gorna-Bania

Reputation: 215

How to check if text is present on a webpage?

how to check if text is present on a webpage using php and if true to execute some code?

My idea is to show some relevant products on the confirmation page after completing an order - if the name of the product is present on the page, then load some products. But I can't make the check for present text.

Upvotes: 1

Views: 1395

Answers (3)

Accountant م
Accountant م

Reputation: 7483

Case 1 if you prepare your page in a variable then echo it at the end of the script like

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

then you can merely search the string with any string search function

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


Case 2 if you don't prepare the page in a string . and you just echo the contents and output the contents outside the <?php ?> tags like

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

Then you have no way to catch the text you want unless you use output buffering


Case 3 if you use output buffering - which I suggest - like

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

then you can search the output anytime you want

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

Upvotes: 1

Fastest solution is using php DOM parser:

$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;
}

This way, variable $txt would hold the text content of a given webpage, as long as it is enclosed around div tags, as usually. Good luck!

Upvotes: 0

Poiz
Poiz

Reputation: 7617

You may need to buffer your Output like so...

<?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;

Upvotes: 0

Related Questions