开发者

Separating txt file to many csv files with PHP

So I was able to parse the txt file into a csv file

$data = array();
while ($line= fgets ($fh)) {
$stack = array($LAUS,$FIPS,$CountyName,$Date,$_CLF,$_EMP,$_UNEMP,$RATE);
        array_push($data, $stack);
}
$file = fopen('file.csv','w');

foreach ($data as $fields) {
fputcsv($file, $fields,',','"');
 }

fclos开发者_开发技巧e($file);

My question is, what is the best way to create multiple csv files that are seperated by Month (also the year, like Jan01.csv, Jan02.csv).


I'm taking a bit of a guess at the formatting of your date

while ($line = fgets ($fh)) {
    // Not sure where you're getting these values, but I'm assuming it's correct
    $stack = array($LAUS,$FIPS,$CountyName,$Date,$_CLF,$_EMP,$_UNEMP,$RATE);

    // Assuming $Date looks like this '2011-10-04 15:00:00'
    $filename = date('My', strtotime($Date)) . '.csv';
    $file = fopen($filename,'a+');
    fputcsv($file, $stack,',','"');
    fclose($file);
}

This will be a little slow since you're opening and closing files constantly, but since I don't know the size of your original data set I don't want to use up all the memory caching the result before I write it.

Be aware that running this multiple times will end up with duplicate data being inserted into your CSV files. You may want to add some code to remove/clear out any currently existing CSV files before you run this bit of code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜