使用PHP将txt文件分离为多个csv文件

发布于 2024-12-08 00:03:26 字数 394 浏览 0 评论 0原文

所以我能够将 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);

我的问题是,创建按月份(也是年份,如 Jan01.csv、Jan02.csv)分隔的多个 csv 文件的最佳方法是什么。

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,',','"');
 }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘香 2024-12-15 00:03:26

我对您的日期格式进行了一些猜测

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);
}

这会有点慢,因为您不断打开和关闭文件,但由于我不知道您的原始数据集的大小,我不想要在写入结果之前用完所有缓存结果的内存。

请注意,多次运行此操作最终会导致重复数据被插入到 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. You may want to add some code to remove/clear out any currently existing CSV files before you run this bit of code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文