I have a small problem. I need to get a line from a text file using PHP. Here is an example of the text file:
hello 2010-10-25
hello 2010-10-26
hello 2010-10-27
hello 2010-10-28
hello 2010-10-29
hello 2010-10-30
hello 2010-10-31
And my code for taking out a the line which contains "2010-10-26" is this:
<?php
$datefile = fopen('file.txt', 'r') or exit("Unable to open file.txt");
while(!feof($datefile))
{
$date = "2010-10-26";
$string = fgets($datefile);
if(strpos($string, $date)==true)
{
echo fgets($datefile);
}
}
fclose($datefile);
?>
Instead of printing out the line "hello 2010-10-26", it prints out "hello 2010-10-27" I have no idea whats going on, please help.
When finding the row, you read the next line and return it.
echo fgets($datefile);
Instead you want to return the current line
echo $string;
Well like kingCrunch said instead of usingecho fgets($datefile);
use
echo $string;
or if you still want to use what you have been using, then set the date variable to a day less than what you want to get.
Hint: Its much more easier to use file()
to read a lines of a file into an array.
Example:
$date = '2010-10-26';
foreach (file('file.txt') as $line) {
if ($line == $date) {
echo 'Match: '.$line;
break;
}
}
Or even shorter:
$date = '2010-10-26';
$lines = file('file.txt');
if (in_array('hello '.$date, $lines)) {
echo 'Match '.$date;
}