我需要做的是,每次运行testdata.csv时,都能够将第一行从.php移动到另一个具有testdata_new.csv名称的.csv (附加数据)。
这是一个包含姓名、年龄、职务的数据示例。
示例数据testdata.csv:
约翰,32岁,科学家 玛丽,25岁,雇主 尼克,36岁,设计师 Miky,46岁,销售人员 Alex,29岁,后勤部
这就是运行它的.php所要做的:从testdata.csv(32岁的科学家约翰)中剪切第一行,并将其粘贴到第一行(标头)下的新testdata_new.csv中,这个新testdata_new.csv将始终是“命名年龄作业”。用剩下的行保存testdata_new.csv和testdata.csv。
我做了一些测试,但离解决方案还有很远的距离。
<?php
$file = "testdata.csv";
$f = fopen($file, "r");
$i = 0;
$file2 = str_replace(".csv", "_new.csv", $file);
$f2 = fopen($file2,"a");
while ($i<2) {
$record = fgetcsv($f);
foreach($record as $field) {
echo $field . "<br>";
}
$i++;
}
fwrite($f2,fread($f, filesize($file)));
fclose($f);
fclose($f2);
?>执行该脚本将显示template.csv文件的第一行,并将生成另一个名为template_new.csv的文件,其中包含以下行:
玛丽,25岁,雇主 尼克,36岁,设计师 Miky,46岁,销售人员 Alex,29岁,后勤部
我真正需要的是在template_new.csv文件中显示的第一行:
约翰,32岁,科学家
并再次保存没有第一行的template.csv,因为其思想是剪切和粘贴行,如下所示:
玛丽,25岁,雇主 尼克,36岁,设计师 Miky,46岁,销售人员 Alex,29岁,后勤部
提前感谢大家的帮助!
发布于 2017-07-06 16:23:55
如此简单;-)
$old_file = 'testdata.csv';
$new_file = 'testdata_new.csv';
$file_to_read = file_get_contents($old_file); // Reading entire file
$lines_to_read = explode("\n", $file_to_read); // Creating array of lines
if ( $lines_to_read == '' ) die('EOF'); // No data
$line_to_append = array_shift( $lines_to_read ); // Extracting first line
$file_to_append = file_get_contents($new_file); // Reading entire file
if ( substr($file_to_append, -1, 1) != "\n" ) $file_to_append.="\n"; // If new file doesn't ends in new line I add it
// Writing files
file_put_contents($new_file, $file_to_append . $line_to_append . "\n");
file_put_contents($old_file, implode("\n", $lines_to_read));https://stackoverflow.com/questions/44948408
复制相似问题