merging multiple csv files using php

2019-06-05 22:09发布

问题:

I want to create a command line php script which would merge/join multiple CSV files from a folder into one.

Each CSV file has 2 columns delimited by comma (,) but multiple number of rows varies. Also each of the CSV file name is unique so when we merge the CSV files I want the file name of the CSV to be the first column for each rows in the file.

So eventually when the script it run it’ll join multiple CSV files under a folder to one. From 2 columns the output file will have 3 columns where the first column would be the file name.

回答1:

<?php
    $nn = 0;
    foreach (glob("*.csv") as $filename) {

        if (($handle = fopen($filename, "r")) !== FALSE) {

            while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
                $c = count($data);
                $csvarray[$nn][] = $filename;
                for ($x=0;$x<$c;$x++)
                {
                    $csvarray[$nn][] = $data[$x];
                }
                $nn++;
            }

            fclose($handle);
        }

    }

    $fp = fopen('../file.csv', 'w');//output file set here

    foreach ($csvarray as $fields) {
        fputcsv($fp, $fields);
    }

    fclose($fp);

?>

I didn't make any test on it though, here is the logic and code you can follow.