I am trying to search a text file for a string, and then display only the one line that was found. Would like to display the found line in a label box. My PHP is really weak. I got the following code working which will display the first line in the text area. Below is the contents of the text file: test.txt
First line
Second Line
Third Line
Fourth Line
My code is as follows:
<!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
</body>
</html>
This code returns First Line into the text area, so how can I return First Line to text box, label?
Any pointer toward the right direction?
Thanks Mitch
CodePudding user response:
You'd want to continue fgets($file)
in a loop, and checking if the search string is in the result, then when the search string is found, echo the line. Something like this maybe...
while ( $line = fgets( $myfile ) ) {
if ( str_contains( $line, $search_string ) ) {
echo $line;
break;
}
}
Note that str_contains
is php 8 and up only. There are other methods for lower versions.
Also consider that perhaps a database would be better for this type of operation rather than using a flat file...