【问题标题】:How to edit a particular line of the csv file using PHP?如何使用 PHP 编辑 csv 文件的特定行?
【发布时间】:2013-06-17 14:24:29
【问题描述】:

我有一个 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 步骤。

【问题讨论】:

  • 你在这里有正确的想法,但我可以建议使用fopen 选项w+ 或类似的,这样你就不需要第二个文件句柄来写入文件。键入r 仅打开文件以供阅读。

标签: php csv


【解决方案1】:

我能想到的方法之一如下:

  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. 喝一品脱。 :)

这是代码(减去用于读取的循环):

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

【讨论】:

  • 你解释得很漂亮你也可以放代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
相关资源
最近更新 更多