0

i have below mentioned search code for keyword from given pages in the $pages array variable, it is working as i want, but it taking so much time to load because there are multiple pages in $pages array. how to increase this speed? please let me know.

<?php 
$match="";
 if(isset($_POST['submit'])){
     if(isset($_POST['txt_search'])){
         $match=trim($_POST['txt_search']);
     }
     if($match==""){
       print "Please enter search text";exit;
     }
 }     
<html>
  <body>    
    <form action="" method="post">
      <input type="text" name="txt_search" placeholder="Search term"/>
      <input type="submit" value="Search" name="submit" onClick=""/>
    </form>
    <p id="text">
       <?php if($match!=""){
          mastersearch($match);
       }?>
    </p>
  </body>
</html>
<?php
 function mastersearch($match) {
    $pages=array("index.php","about.php","contact.php","books.php","careers.php","shopping.php","travels.php","lifestyle.php","movies.php","museum.php");
    foreach ($pages as $value) {
        $text=$value; 
        $path="http://sitename.com/user/";
        $value = $path.$value;
        $json = file_get_contents($value);
        $lastPos=0;
        $last=strripos($json, $match);
        while (($lastPos = stripos($json, $match, $lastPos))!== false) {
            $positions[] = $lastPos;
            preg_match("/<title>(.*)<\/title>/i", $json, $title);
            print $title[1];
            print "<br><a href='$value'>$text</a><br/>";
            $lastPos = $lastPos + strlen($match);
        }
    }
 }
?>
  • Search services like SOLR usually keep a (reasonably) up to date index of all the keywords they found in each page. To speed your code up you can just use such a service and update it via a scheduled task which would run every say 1 hour or whenever content is created/updated. – apokryfos Aug 03 '17 at 07:13

1 Answers1

0

if you time your script, i assume that the file_get_contents() call is the expensive one. It depends on your connection to the remote site so in order to speed things up you could improve that connection or introduce some sort of cache

BNT
  • 936
  • 10
  • 27