PHP如何获取文件中的行数并将文件指针移动到指定行?
有没有办法:PHP如何获取文件中的行数并将文件指针移动到指定行?,php,filesystems,flat-file,Php,Filesystems,Flat File,有没有办法: 计算我的small_db.php中的行数(1行=数据行) 告诉PHP将文件指针精确地移动到第322行的开头。(这样我就可以从此行中获取fgets()数据) 告诉PHP返回行号或出现文本“QuickBrownFox”的行的全部内容 我知道还有另一种方法可以在一个字符串中获取文件的所有内容,但正如您所知,如果文件的大小很大,则该方法的时间和内存效率都很低。首先,这里是一些基本变量: $filename = 'small_db.php'; $linenum = 322; $needle
我知道还有另一种方法可以在一个字符串中获取文件的所有内容,但正如您所知,如果文件的大小很大,则该方法的时间和内存效率都很低。首先,这里是一些基本变量:
$filename = 'small_db.php';
$linenum = 322;
$needle = 'Quick brown fox';
file()
的返回值。或者,您可以使用标准文件函数、、和来打开文件并逐行读取,同时保持计数,如下所示:
$count = 0;
$fp = fopen( $filename, 'r');
while( !feof( $fp)) {
fgets( $fp);
$count++;
}
fclose( $fp);
// Create a new object for the file
$file = new SplFileObject( $filename);
// Seek to to the specific line number
$file->seek( $linenum);
// Print that line:
echo 'Line #' . $file->key() . ' contains: ' . $file->current();
$count = 0;
$fp = fopen( $filename, 'r');
while( !feof( $fp)) {
fgets( $fp);
$count++;
}
fclose( $fp);
// Create a new object for the file
$file = new SplFileObject( $filename);
// Seek to to the specific line number
$file->seek( $linenum);
// Print that line:
echo 'Line #' . $file->key() . ' contains: ' . $file->current();
$fp
给出),并使用特定的区分大小写$needle
进行检查(可用于不区分大小写的搜索):
您需要这样调用此函数:
$fp = fopen( $filename, 'r');
$return = find_in_file( $fp, $needle);
if( !is_null( $return)) {
echo 'Found ' . $needle . ' in line #' . $return['line_number'] . "\n";
echo 'That line contains: ' . $return['line'];
}
fclose( $fp);
不久前,我写了一篇博客文章,解释了如何使用PHP截短文件的最后N行,我认为同样的逻辑将有助于您实现所需: