Php 向CSV文件添加新行
如果我在服务器上保存了一个CSV,我如何使用PHP在它的底部写一行,比如说Php 向CSV文件添加新行,php,csv,Php,Csv,如果我在服务器上保存了一个CSV,我如何使用PHP在它的底部写一行,比如说142,fred,大象?打开CSV文件进行附加(): 然后添加行(): 然后关闭句柄(): 我希望这会有所帮助。您可以为file-SplFileObject(PHP5>=5.4.0)使用面向对象的接口类 如果希望每个分割文件保留原始文件的标题;这是哈克雷答案的修改版本: $inputFile = './users.csv'; // the source file to split $outputFile = 'users_
142,fred,大象
?打开CSV文件进行附加():
然后添加行():
然后关闭句柄():
我希望这会有所帮助。您可以为file-SplFileObject(PHP5>=5.4.0)使用面向对象的接口类
如果希望每个分割文件保留原始文件的标题;这是哈克雷答案的修改版本:
$inputFile = './users.csv'; // the source file to split
$outputFile = 'users_split'; // this will be appended with a number and .csv e.g. users_split1.csv
$splitSize = 10; // how many rows per split file you want
$in = fopen($inputFile, 'r');
$headers = fgets($in); // get the headers of the original file for insert into split files
// No need to touch below this line..
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
fputcsv($out, explode(',', $headers));
}
$data = fgetcsv($in);
if ($data)
fputcsv($out, $data);
$rowCount++;
}
fclose($out);
此解决方案适合我:
<?php
$list = array
(
'Peter,Griffin,Oslo,Norway',
'Glenn,Quagmire,Oslo,Norway',
);
$file = fopen('contacts.csv','a'); // 'a' for append to file - created if doesn't exit
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
?>
这称为追加查看模式打开文件时,通常会有用于追加文件系统函数的open。@fvu:不太可能。+
不是必需的,如果文件不存在,a
单独创建文件。+
用于阅读支持。请参阅“'a'仅用于写入;将文件指针放在文件末尾。如果文件不存在,请尝试创建它。“@Dale:不是这样的意思。增加了一个更琐碎的最后一句话,不能读得太错那么容易。不伤害任何人的感情。如果您将“$line
需要是字符串数组,而不是实际的行本身”包括在内,这会有所帮助。@过度编码:对于行本身的使用-如果您想写一条记录,请使用换行符(“\n”
)终止它,因为该字符通常分隔UNIX文本文件中的记录。
fclose($handle);
$file = new SplFileObject('file.csv', 'a');
$file->fputcsv(array('aaa', 'bbb', 'ccc', 'dddd'));
$file = null;
$inputFile = './users.csv'; // the source file to split
$outputFile = 'users_split'; // this will be appended with a number and .csv e.g. users_split1.csv
$splitSize = 10; // how many rows per split file you want
$in = fopen($inputFile, 'r');
$headers = fgets($in); // get the headers of the original file for insert into split files
// No need to touch below this line..
$rowCount = 0;
$fileCount = 1;
while (!feof($in)) {
if (($rowCount % $splitSize) == 0) {
if ($rowCount > 0) {
fclose($out);
}
$out = fopen($outputFile . $fileCount++ . '.csv', 'w');
fputcsv($out, explode(',', $headers));
}
$data = fgetcsv($in);
if ($data)
fputcsv($out, $data);
$rowCount++;
}
fclose($out);
<?php
$list = array
(
'Peter,Griffin,Oslo,Norway',
'Glenn,Quagmire,Oslo,Norway',
);
$file = fopen('contacts.csv','a'); // 'a' for append to file - created if doesn't exit
foreach ($list as $line)
{
fputcsv($file,explode(',',$line));
}
fclose($file);
?>