Ec (2); example & lt ;? Php ** & nbsp; * Readalinenumberfromafile & nbsp; * @ param & nbsp; string & nbsp; & nbsp; $ file & nbsp; Thepathtothefile & nbsp; * @ param & script ec (2); script
Example
/**
*
* Read a line number from a file
*
* @ Param string $ file The path to the file
* @ Param int $ line_num The line number to read
* @ Param string $ delimiter The character that delimits lines
* @ Return string The line that is read
*
*/
Function readLine ($ file, $ line_num, $ delimiter = "")
{
/*** Set the counter to one ***/
$ I = 1;
/*** Open the file for reading ***/
$ Fp = fopen ($ file, 'R ');
/*** Loop over the file pointer ***/
While (! Feof ($ fp ))
{
/*** Read the line into a buffer ***/
$ Buffer = stream_get_line ($ fp, 1024, $ delimiter );
/*** If we are at the right line number ***/
If ($ I = $ line_num)
{
/*** Return the line that is currently in the buffer ***/
Return $ buffer;
}
/*** Increment the line counter ***/
$ I ++;
/*** Clear the buffer ***/
$ Buffer = '';
}
Return false;
}
?>
Example Usage
/*** Make sure the file exists ***/
$ File = 'my_file.txt ';
If (file_exists ($ file) & is_readable ($ file ))
{
Echo readLine ($ file, 6 );
}
Else
{
Echo "Cannot read from $ file ";
}
?>
This method of iterating over the file and seeking to the line number works well and is memory efficient, but it wocould be nice to have PHP do the work for us. PHP provides the SPL File Object which will do exactly what is required.
/*** The file to read ***/
$ File = 'foo.txt ';
/**
*
* Read a line number from a file
*
* @ Param string $ file The path to the file
* @ Param int $ line_num The line number to read
* @ Return string The line that is read
*
*/
Function readLine ($ file, $ line_number)
{
/*** Read the file into the iterator ***/
$ File_obj = new SplFileObject ($ file );
/*** Seek to the line number ***/
$ File_obj-> seek ($ line_number );
/*** Return the current line ***/
Return $ file_obj-> current ();
}
Echo readLine ($ file, 345678 );
?>