0

I have a html search box that uses the script below, but it seems like the echo output goes in a loop or shows all results from the .txt file that you can see I am using fopen for. I tried to add exit at the end of the echo's but then it was only able to get the first line in content.txt no matter what I searched for using the search box. I am trying to have it only show the result of what being searched for.

Here is the code I've been working on:

<?php
$q = $_REQUEST["q"];
$f = fopen("content.txt", "r");
while (($line = fgets($f)) !== FALSE) {

    if (strstr($line, $q)) {
        echo "<li>Found $line</li>";
    } else {
        echo "<p>Nothing found.</p>";
    }

}

?>
Martin
  • 39
  • 7
  • You can use if statement instead of while loop – Akshay Khale Mar 25 '16 at 04:53
  • @akshaykhale Hmm, I just tested that. It seems like it's only able to get the result for the first line in the txt file. – Martin Mar 25 '16 at 05:01
  • Check the answers. At least one of them would answer your question. If they do not work. add the error you are getting in the comment below each answer. – Mawia HL Mar 25 '16 at 05:25

3 Answers3

0

Try like this

<?php
    $q = $_REQUEST["q"];
    $f = fopen("test.txt", "r");
    $found = false;
    while (($line = fgets($f)) !== FALSE) {
        if (strstr($line, $q)) {
            echo "<li>Found $line</li>";
            $found = true;
        }
    }
    if (!$found){
        echo "<p>Nothing found.</p>";
    }
?>
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

PHP has a built in function for pattern searching. You might find an answer here. PHP to search within txt file and echo the whole line

Community
  • 1
  • 1
srccode
  • 721
  • 4
  • 16
0

Since you are trying to get all the result found in the text file create a blank string and concat it in the loop if result is there echo the result else the no result found.

<?php
$str='';
$q = $_REQUEST["q"];
$f = fopen("content.txt", "r");
while (($line = fgets($f)) !== FALSE) {

    if (strstr($line, $q)) {
        $str.="<li>Found $line</li>";
    }

}
if($str==''){
    echo "<p>Nothing found.</p>";
}else {
   echo $str;
}

?>
Rahul Singh
  • 918
  • 14
  • 31