I’ve found several useful and helpful tutorials and forum posts on this subject. But none I could find display an exact example and implementation of my current scenario.
I am trying to convert my completed query results array into csv format, so I can download the results, properly formatted, in .csv format.
Below is my code:
This is my download action:
<script>
function getcsv(){
window.location="script_4.php";
}
</script>
<input type="button" onclick="getcsv()" value="Download CSV">
This is my while() loop merging my query data into a sequential numeric array:
while ($row = mysql_fetch_row($result)) {
$industries = explode(",", $row[3]);
unset($row[3]);
$merge = array_merge($row, $industries);
echo "<pre>";
print_r($merge);
echo "</pre>";
}
My print_r() above echoes out like this:
Array
(
[0] => 3561
[1] => The Ace Company
[2] => ace@not-a-real-site.com
[3] => Waterproofing
)
Array
(
[0] => 3562
[1] => JOJO Associates, Inc.
[2] => joj@not-a-real-site.com
[3] => Lab Equipment & Casework
)
Array
(
[0] => 3564
[1] => Southern Style Pipe
[2] => southern@no-a-real-site.com
[3] => Plumbing
[4] => Piping
[5] => Pipe Inspection
)
This is where I am at with the download script, and when I attempt it it loads my html and entire array into the csv with no csv formatting of array data.
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
outputCSV($merge);
function outputCSV($data) {
$outstream = fopen("php://output", "w");
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals);
}
array_walk($data, "__outputCSV", $outstream);
fclose($outstream);
}
I solved the problem like so: