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