AutoMate
AutoMate

Reputation: 71

Saving specific columns of CSV to another CSV file in PHP

so trying to read a csv file and extracting details from the file and wish to store specific columns of the csv to another csv file.

I have managed to extract the specific columns of the input csv file but not really sure how I can write those extracted columns to another csv file.

Here is the part of my work:

$row = 1;
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        echo $data[0] . "\n" . $data[1] . "<br />\n";

    }
    $file = fopen("editedTable.csv","w");
    foreach ( $data as $line) {             //working on this part of the code
        fputcsv($file, explode(',',$line));
    }
    fclose($handle);
}

Obviously there is an error in the foreach loop as I am trying to work out the logic.

The data that is extracted is basically first and the second column (data[0], data[1]). Just need this to write to another CSV file. The input csv is just a comma delimited file with 5 columns. Any idea how I can modify the foreach loop and the use the fputcsv method?

Thanks

Upvotes: 0

Views: 941

Answers (2)

Anupam Rekha
Anupam Rekha

Reputation: 186

Because you place the fputs outside of the $data initial loop, you catch only one row, here is the modified code.

     $row = 1;
     $file = fopen("editedTable.csv","w");

    if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            $row++;
            echo $data[0] . "\n" . $data[1] . "<br />\n";
            $line = $data[0].", ".$data[1];
            $line .=  "\n";
            fputs($file, $line);
       }
      fclose($handle);
   }
   fclose($file);

Upvotes: 1

Kerkouch
Kerkouch

Reputation: 1456

fputcsv accepts an array on the second parameter.

I think this is what you looking for:

<?php
$file = fopen("editedTable.csv","w");
$row = 1;
if (($handle = fopen("testtable.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000)) !== FALSE) {
        $num = count($data);
        $row++;
        echo $data[0] . "\n" . $data[1] . "<br />\n";
        fputcsv($file, [$data[0], $data[1]]);
    }
}
fclose($handle);
fclose($file);

Upvotes: 1

Related Questions