简体   繁体   中英

Can't write csv to .txt file? PHP

I am trying to use the putcsv function in php to write an array to a text file but the file is blank, I tried changing the extension to .csv and it works but I need to write it to .txt as per specifications of my assignment. I attempted to change the filename to .csv then write to it then back to .txt, my filesize changed but the file is still blank.

Here is my code

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

I got your problem, if its not allow to write CSV format to text file then write in to CSV file and rename(using rename() in PHP) to text file after writing in to CSV is done.

Here is my sample code:

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

Let me know, if your problem is solved.

Second Method:

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

Simply you can call

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM