无法将 csv 写入 .txt 文件? PHP

Can't write csv to .txt file? PHP

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

这是我的代码

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

我遇到了你的问题,如果它不允许将 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);

使用 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);