【问题标题】:Can't write csv to .txt file? PHP无法将 csv 写入 .txt 文件? PHP
【发布时间】:2015-10-24 05:06:40
【问题描述】:

我正在尝试使用 php 中的 putcsv 函数将数组写入文本文件但文件为空白,我尝试将扩展名更改为 .csv 并且它有效但我需要将其写入 @987654324 @根据我的任务规范。我试图将文件名更改为 .csv 然后写入它然后返回 .txt,我的文件大小已更改但文件仍为空白。

这是我的代码

$fp = fopen('logfile.txt','w') or die ('No file!!!');
      fputcsv($fp,$csv);
      fclose($fp);

【问题讨论】:

标签: php file fputcsv


【解决方案1】:

我遇到了你的问题,如果它不允许将 CSV 格式写入文本文件,则写入 CSV 文件并在写入 CSV 完成后重命名(在 PHP 中使用 rename())到文本文件。

这是我的示例代码:

$fp = fopen('logfile.csv','w') or die ('No file!!!');
fputcsv($fp,$csv);
fclose($fp);
rename('logfile.csv','logfile.txt');

如果您的问题解决了,请告诉我。

第二种方法:

str_putcsv()

function str_putcsv($fields, $delimiter = ',', $enclosure = '"', $escape_char = '\\' ) {
    foreach ($fields as &$field) {
        $field = str_replace($enclosure, $escape_char.$enclosure, $field);
        $field = $enclosure . $field . $enclosure;
    }
    return implode($delimiter, $fields) . "\n";
}

只需调用即可

$file = fopen("newfile.txt", "w") or die("Unable to open file!");
$csvStr = str_putcsv($csv);
fwrite($file, $csvStr);
fclose($fp);

【讨论】:

  • 太棒了,这是一个非常容易实施的解决方案!
  • 不幸的是它没有解决它改变了文件大小但文件没有文本
【解决方案2】:

使用 fwrite()

 $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
 $txt = "John Doe\n";
 fwrite($myfile, $txt);
 $txt = "Jane Doe\n";
 fwrite($myfile, $txt);
 fclose($myfile);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    相关资源
    最近更新 更多