读取CVS文件并将CSV文件输出到.txt文件 [英] Read CVS file and ouput the CSV file to .txt file

查看:138
本文介绍了读取CVS文件并将CSV文件输出到.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在读取CSV文件,并尝试将CS​​V文件数据写入.txt文件.

Hi here I am reading a CSV file and I am trying to write the CSV file data into a .txt file.

    $row = 1;
    if (($handle = fopen("data.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                $myfile = fopen("newfile.txt", "w") or die ("unable to open file");
                fwrite($myfile, $data[$c]);
            }
        }
        fclose($handle);
}

正在创建newfile.txt,并且newfile.txt中仅显示CSV文件中的最后一条记录.谁能告诉我为什么CSV中的所有内容都没有显示在我的newfile.txt中(仅显示最后一条记录).谢谢

The newfile.txt are being created and only the last record in the CSV file are showing in the newfile.txt. Can anyone tell me why everything in the CSV are not showing in my newfile.txt(only the last record are displaying). Thank You

推荐答案

您只需打开一次新文件.

You only need to open the new file once.

$row = 1;
if (($handle = fopen("data.csv", "r")) && $myfile = fopen("newfile.txt", "w")) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        fputcsv($myfile, $data);
    }
    fclose($handle);
    fclose($myfile);
}

这篇关于读取CVS文件并将CSV文件输出到.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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