[英]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
步骤,则可以优化此步骤。
我能想到的方法之一是:
fgets()
获取文件的第一行(而不是fgetcsv()
)。 str_getcsv()
解析该行。 fopen()
读取原始CSV文件。 fseek()
将原始CSV文件句柄更改为第一行的长度(在步骤2中保存)+1。 fopen()
用于写入的新CSV文件(实际附加)。 fread()
循环中的原始CSV文件,直到EOF和fwrite()
块入新的CSV文件。 这是代码(减去读取循环):
<?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.