简体   繁体   English

如何使用 PHP 从 CSV 文件读取一系列行到 JSON 数组来处理大型 ZCC8D68C551C4ADEAFDDZD4 文件?

[英]How to read a range of rows from CSV file to JSON array using PHP to handle large CSV file?

The target is how to read a range of rows/lines from large CSV file into a JSON array in order to handle large files and read the data in pagination method, each page fetches a range of lines ( ex page number 1 fetch from line 1 to 10, page number 2 fetch from line 11 to line 20, and so and ).目标是如何从大 CSV 文件中读取一系列行/行到 JSON 数组中,以便处理大文件并以分页方法读取数据,每个页面获取一系列行(例如第 1 页从第 1 行获取到 10,第 2 页从第 11 行取到第 20 行,依此类推)。

the below PHP script read from the being CSV file to the desired line ($desired_line), My question is how we can determine the starting line to read from a specific line ($starting_line)下面的 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));

?>

You should use functions like:您应该使用以下功能:

fgets() to read the file line by line fgets()逐行读取文件

fseek() to move to the position of the last fgets() of the chunk fseek()移动到块的最后一个fgets()的 position

ftell() to read the position for fseek() ftell()fseek()读取 position

Something like this (it's only a schema):像这样的东西(它只是一个模式):

<?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;
   }
}

...

?>

You can also skip the fseek() and ftell() part and just count the lines every time from the beginning, but that will generally have to go through the whole file from the beginning till the desired lines.您也可以跳过fseek()ftell()部分,每次从头开始计算行数,但这通常需要 go 从头到所需的行贯穿整个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM