如何使用PHP编辑csv文件的特定行?

时间:2013-06-17 14:24:30

标签: php csv

我有一个PHP脚本,允许用户上传他们的数据。 csv文件的第一行是标题(fname,lname,age,address,email)。

我的计划是 - 在用户上传他们的csv后,我的脚本将运行一个函数来检查标题的拼写。如果有拼写错误的标题,我的脚本将更正它。我使用下面的代码来更正标题:

   if (($file = fopen($csvFile , "r")) != FALSE) {
        $ctr = 0;
        $record = fgetcsv($file, 1024)) != FALSE) {
            if ($ctr == 0) {
                correctHeader($record);
                # write to new csv.
            } else {
                # write to new csv.
            }
        }
    }

更正后,标题和后续行的值将附加在新的csv文件中。我认为如果我可以编辑csv(标题)的第一行并跳过# write to new csv步骤,则可以优化此步骤。

1 个答案:

答案 0 :(得分:0)

我能想到的其中一个方法如下:

  1. 使用fgets()获取文件的第一行(而不是fgetcsv())。
  2. 以字节为单位保存行的长度。
  3. 使用str_getcsv()解析该行。
  4. 根据需要更正标题。
  5. 将标题保存到新的CSV文件中。
  6. fopen()原始CSV文件供阅读。
  7. fseek()原始CSV文件句柄到第一行的长度(在步骤2中保存)+ 1.
  8. fopen()用于撰写的新CSV文件(实际附加)。
  9. fread()循环中的原始CSV文件,直到EOF和fwrite()分组到新的CSV文件中。
  10. 修复错误。
  11. 喝一品脱。 :)
  12. 这是代码(减去阅读循环):

    <?php
    $from = 'd.csv';
    $to = 'd.good.csv';
    
    $old = fopen($from, 'r');
    if (!is_resource($old)) {
        die("Failed to read from source file: $from");
    }
    
    $headerLine = fgets($old);
    $headerLine = fixHeaders($headerLine);
    
    $new = fopen($to, 'w');
    if (!is_resource($new)) {
        die("Failed to write to destination file: $new");
    }
    // Save the fixed header into the new file
    fputs($new, $headerLine);
    // Read the rest of old and save to new.
    // Old file is already open and we are the second line.
    // For large files, reading should probably be done in the loop with chunks.
    fwrite($new, fread($old, filesize($from)));
    
    // Close files
    fclose($old);
    fclose($new);
    
    // Just an example
    function fixHeaders($line) {
        return strtoupper($line);
    }