Search code examples
phpcsvrowsmove

Move first row from a csv to another using php


What I need to do is to be able to move the first row from a testdata.csv every time I run the .php to another .csv with the name testdata_new.csv(appending data).

This is an example of data that includes Name, Age, Job

Example data testdata.csv:

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

This is what the .php will do running it: Cut the first row from testdata.csv(john,32,scientist) and paste it to the new testdata_new.csv under the first row(header) that will always be "Name Age Job". Save testdata_new.csv and testdata.csv with the remaining rows.

I did some tests but I'm still far away from the solution.

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

?>

Executing the script will display the first row of the template.csv file and will produce another file with the name template_new.csv with the following rows:

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

What I really need to have in the template_new.csv file is only the first row displayed:

John,32,Scientist

And save again the template.csv without the first row as the idea is to cut and paste the rows, as following:

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

Thank you all in advance for your help!


Solution

  • As easy as this ;-)

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