Entry
using fread, is there a way to ensure only one line is read and or that once the single line from a file is read, a carriage return is not inserted?
Mar 16th, 2005 02:25
John Doe, Ben Udall, kerry lutz, http://www.php.net/manual/function.fgets.php
Try using the fgets() function, it won't read past a line. Below is a
small example to read a single line.
$fp = fopen('somefile.txt', 'r');
do {
$line .= fgets($fp, 128);
} while ($line[strlen($line)-1] != "\n");
------------------
Added by dw.no:
You can also split the file into an array and then select the line you
want by refering to $array[$line_number].
There are several ways to do this, file() may be the easiest way, but
you can also use fread().
example:
$filename = '/path/to/file.txt';
// error handling
if (!file_exists($filename)) { die("file doesn't exist"); }
if (filesize($filename) == 0) { die("file is empty"); }
// open the file as read-only
$file = fopen($filename, "r");
// read the entire file
$file_contents = fread($file, filesize($filename));
// Remove carriage returns, but keep line feeds
$file_contents = str_replace("\r\n", "\n", $file_contents);
$file_contents = str_replace("\r", "\n", $file_contents);
// make the array
$file_contents = explode("\n", $file_contents);
// output the first line
echo $file_contents['0'];
// output the sixth line
echo $file_contents['5'];
// output all lines
for ($i=0, $c=count($file_contents); $i < $c; $i++) {
echo $file_contents[$i];
} // end for
http://www.php.net/manual/en/function.fread.php
http://www.php.net/manual/en/function.explode.php
http://www.php.net/manual/en/function.str-replace.php
http://www.php.net/manual/en/control-structures.for.php
http://www.php.net/manual/en/function.file.php