使用php合并多个csv文件 [英] merging multiple csv files using php

查看:1623
本文介绍了使用php合并多个csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个命令行php脚本,它可以将一个文件夹中的多个CSV文件合并/合并为一个。

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

每个CSV文件都有两列由逗号分隔(,),但多行数不同。此外,每个CSV文件名都是唯一的,因此,当我们合并CSV文件时,我想将CSV文件名作为文件中每行的第一列。

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.

所以最终当脚本运行它会将一个文件夹下的多个CSV文件到一个。

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.

推荐答案

<?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.

这篇关于使用php合并多个csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆