I am trying to read in a txt file, convert it to csv and display it in a spreadsheet. There are many example here and I have tried many of them but the result is the same. I seem to have two problems. First, the code I use to convert the csv line adds an extra comma to the end and I can't get it deleted. Second, even when entering a test string the spreadsheet doesn't open.
When I read in my test file I get an array like this:
array [
Hunky Bill's Big Perogie / Pierogi Maker
9
4
10
5
5
1
2
1
]
The code I am using is
$csv_file = 'arry.txt';
$save_name = 'csvout.csv';
if (($fp = fopen($csv_file ,'r'))) {
while(! feof($fp)) {
$item = fgets($fp);
$item = rtrim($item, "\r\n");
$csv_string .= '"' . $item . '",';
// $csv_string = substr($csv_string, 0, -1);
// $csv_string[strlen($csv_string)] = '';
// $csv_string = rtrim($csv_string, ',');
}
fclose($fp);
}
header("Expires: Mon, 26 Nov 2162 00:00:00 GMT");
header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type: Application/octet-stream");
header("Content-Disposition: attachment; filename=$save_name");
echo $csv_string;
Running the above displays this on the screen:
"Hunky Bills Big Perogie Pierogi Maker","9","4","10","5","5","1","2","1","","",
If I uncomment any of the three lines meant to remove that last comma, all of the commas are removed. Why is that?
If I skip the above and just enter this line before the echo statement, the spreadsheet still doesn't open. Should it open in the spreadsheet program?
$csv_string = '"Hunky Bills Big Perogie Pierogi Maker","9","4","10","5","5","1","2","1"';
Can anyone see where my problems are?