Converting PHP Arrays to CSV Files
Converting an array of products to a CSV file can be a straightforward process, but errors can arise if the file ends up as a single long line or if the header does not initiate a download.
One solution to the single-line issue is to utilize the fputcsv() function instead of manually writing out values. By using fputcsv(), you can easily format data into a CSV-compatible structure. The code can be improved as follows:
[...]
$output = fopen("php://output",'w') or die("Can't open php://output");
header("Content-Type:application/csv");
header("Content-Disposition:attachment;filename=pressurecsv.csv");
fputcsv($output, array('id','name','description'));
foreach($prod as $product) {
fputcsv($output, $product);
}
fclose($output) or die("Can't close php://output");
Another potential issue is ensuring that the header forces a download. To achieve this, add the following headers to your PHP script:
[...]
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
[...]
By incorporating these modifications, your PHP script should now successfully convert the array of products into a CSV file, with the header prompting a download.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3