繁体   English   中英

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

[英]How to edit a particular line of the csv file using PHP?

我有一个PHP脚本,允许用户上传数据。 csv文件的第一行是标头(fname,lname,age,地址,电子邮件)。

我的计划是-在用户上传其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. 使用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);
}

暂无
暂无

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

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