[英]Separating txt file to many csv files with PHP
So I was able to parse the txt file into a csv file 所以我能够将txt文件解析为csv文件
$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,',','"');
}
fclose($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). 我的问题是,创建多个按月(也就是年份,如Jan01.csv,Jan02.csv)分隔的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. 请注意,多次运行将导致重复数据插入到CSV文件中。 You may want to add some code to remove/clear out any currently existing CSV files before you run this bit of code.
在运行这段代码之前,您可能需要添加一些代码以删除/清除任何当前存在的CSV文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.