【问题标题】:Read CVS file and ouput the CSV file to .txt file读取 CSV 文件并将 CSV 文件输出到 .txt 文件
【发布时间】:2014-11-17 13:29:35
【问题描述】:

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

    $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,只有 CSV 文件中的最后一条记录显示在 newfile.txt 中。谁能告诉我为什么 CSV 中的所有内容都没有显示在我的 newfile.txt 中(仅显示最后一条记录)。谢谢你

【问题讨论】:

  • 这可能是因为它重写了同一行。尝试将所有字符串放在一起,只写一个大字符串。

标签: php csv


【解决方案1】:

您只需打开新文件一次。

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

【讨论】:

    【解决方案2】:

    使用a+ 参数打开您的文件,而不是w for fopen

    the doc 开始,“w”模式仅用于写入,而“a+”模式用于读取和写入,并将文件指针放在文件末尾。如果文件不存在,它会尝试创建它。

    $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", "a+") or die ("unable to open file");
                fwrite($myfile, $data[$c]);
            }
        }
        fclose($handle);
    }
    

    【讨论】:

      【解决方案3】:
      1. 您在每次循环迭代时都打开文件,尝试将其放在循环上方不是一个好主意
      2. 在 fopen reference 中使用 a+ 模式而不是 w

      【讨论】:

        【解决方案4】:

        这可能是因为您每次写入记录并覆盖其内容时都会重新打开文本文件。要么以附加模式打开文件(不能告诉你怎么做,我不是 php 程序员),要么只打开你的文本文件一次并在一个会话中写入多次。

        编辑:您应该使用 'a' 或 'a+' 而不是 'w' 作为 fopen 的参数,如下所述:http://php.net/manual/en/function.fopen.php

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-17
          • 1970-01-01
          • 1970-01-01
          • 2014-02-26
          • 1970-01-01
          • 2014-09-15
          相关资源
          最近更新 更多