使用 php 将第一行从 csv 移动到另一个

Move first row from a csv to another using php

我需要做的是每次我 运行 .php 将第一行从 testdata.csv 移动到另一个名为 testdata_new.csv(附加数据)。

这是一个包含姓名、年龄、工作的数据示例

示例数据testdata.csv:

John,32,Scientist
Mary,25,Employer
Nick,36,Designer
Miky,46,Sales
Alex,29,Logistics

这就是 .php 运行 将执行的操作: 从 testdata.csv(john,32,scientist) 中剪切第一行并将其粘贴到第一行 (header) 下的新 testdata_new.csv,该行将始终为 "Name Age Job"。 保存 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 的文件,其中包含以下行:

Mary,25,Employer
Nick,36,Designer
Miky,46,Sales
Alex,29,Logistics

我真正需要在 template_new.csv 文件中的只是显示的第一行:

John,32,Scientist

并再次保存没有第一行的 template.csv 因为想法是剪切和粘贴行,如下所示:

Mary,25,Employer
Nick,36,Designer
Miky,46,Sales
Alex,29,Logistics

提前感谢大家的帮助!

就这么简单 ;-)

$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));