[英]How to read a range of rows from CSV file to JSON array using PHP to handle large CSV file?
目标是如何从大 CSV 文件中读取一系列行/行到 JSON 数组中,以便处理大文件并以分页方法读取数据,每个页面获取一系列行(例如第 1 页从第 1 行获取到 10,第 2 页从第 11 行取到第 20 行,依此类推)。
下面的 PHP 脚本从 CSV 文件读取到所需的行($desired_line),我的问题是我们如何确定从特定行读取的起始行($starting_line)
<?php
// php function to convert csv to json format
function csvToJson($fname, $starting_line, $desired_line) {
// open csv file
if (!($fp = fopen($fname, 'r'))) {
die("Can't open file...");
}
//read csv headers
$key = fgetcsv($fp,"1024","\t");
$line_counter = 0;
// parse csv rows into array
$json = array();
while (($row = fgetcsv($fp,"1024","\t")) && ($line_counter < $desired_line)) {
$json[] = array_combine($key, $row);
$line_counter++;
}
// release file handle
fclose($fp);
// encode array to json
return json_encode($json);
}
// Define the path to CSV file
$csv = 'file.csv';
print_r(csvToJson($csv, 20, 30));
?>
您应该使用以下功能:
fgets()
逐行读取文件
fseek()
移动到块的最后一个fgets()
的 position
ftell()
为fseek()
读取 position
像这样的东西(它只是一个模式):
<?php
...
$line_counter = 0;
$last_pos = ...
$fseek($fp,$last_pos);
while($line = fgets($fp)){ // read a line of the file
$line_counter++;
(...) // parse line of csv here
if($line_counter == 100){
$lastpos = ftell($fp);
(...) // save the $lastpos for next reading cycle
break;
}
}
...
?>
您也可以跳过fseek()
和ftell()
部分,每次从头开始计算行数,但这通常需要 go 从头到所需的行贯穿整个文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.