1

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.