例子
/**
*
* 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 would 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 );
?>

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。