Forum Moderators: coopster
I am trying to generate a file with php from a database extract that i would like to be open in excel.
What i need is to format the content of the file in CSV i guess. The 'fgetcsv()' can do the job by formating the content of an existing file.
Is there an other option than to create a file with my database content, save it on the server and open/format it with 'fgetcsv()'?
Thanks a lot for your help.
Assuming the data is in a 2D array, you can do something like:
$data=Array(.... balh blahb.... (2D));
$fh=fopen("filepath.csv","w");
foreach ($data as $row)
{
$row="";
foreach ($row as $point)
{
$row[]=csvquote($point);
}
fwrite($fh,implode(",",$row)."\n\r");
}
fclose($fh);
Look into content-type headers which will make excel open it straight away :)
The function csvquote could be:-
function csvquote($string)
{
if (!preg_match("/[^0-9]/",$string)) return $string; //num
else return "\"".addslashes(preg_replace("/([\n\r])/","\\$1",$string))."\"";
}