我正在尝试做这个确切的功能,只想能够显示文档的最后20行?
$file = fopen("/tmp/$importedFile.csv","r");
while ($line = fgetcsv($file))
{
$i++;
$body_data['csv_preview'][] = $line;
if ($i > 20) break;
}
fclose($file);我已经尝试过在$file = fopen("/tmp/$importedFile.csv","r");中更改"r",但是似乎只有将指针放在读和写的位置的变化。
我觉得这可能很简单。我很抱歉。
发布于 2012-07-25 21:42:28
实现这一点的一种方法是使用SqlFileObject。首先,您需要知道文件中有多少行,您可以这样计算:
$filename = "/tmp/$importedFile.csv";
// Create a new object for the file
$file = new SplFileObject( $filename, "r");
$lines = 0;
while ( !$file->eof()) {
$file->fgets();
$lines++;
}现在您知道文件中有$lines行数了。然后,您必须查找$lines - 20行号,并读取您的CSV数据,直到EOF,如下所示:
$file->seek( $lines - 20);
while ( !$file->eof()) {
$body_data['csv_preview'][] = $file->fgetcsv();
}也许有一种更有效的方法来计算$lines。此外,在尝试通过seek()连接到$lines - 20之前,您应该确认文件中的行数超过20行。
发布于 2012-07-25 21:39:34
您的代码返回前20行。尝试对最后20行进行修改
if($i > 20)
array_shift($body_data['csv_preview'])发布于 2012-07-25 22:14:00
我想出了这个:
$file = fopen("/tmp/$importedFile.csv","r");
$start = count( file( $file ) ) - 20;
$i = 0;
while ($line = fgetcsv($file)) {
$i++;
if ( $i > $start ) $body_data['csv_preview'][] = $line;
}
fclose($file);
//Body_data has now the last 20 lines.希望这能有所帮助
https://stackoverflow.com/questions/11650880
复制相似问题