Converting arrays to CSV files in PHP can be a pain. If you've been struggling to produce a properly formatted CSV, this article will provide a better solution.
Consider the following code:
<code class="php">$prods = [1, 2, 3]; foreach ($prods as $prod) { $sql = "SELECT * FROM products WHERE id = '$prod'"; $result = $mysqli->query($sql); $info = $result->fetch_array(); } // ... rest of the code</code>
This code may result in a CSV file that is a single, long line instead of the desired format with headers and line breaks.
To fix this issue, replace the code that writes to the CSV file with the following:
<code class="php">$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");</code>
The fputcsv() function automatically handles escaping, field delimiters, and line endings, ensuring the CSV is properly formatted.
The above is the detailed content of How to Convert a PHP Array to a Well-Formatted CSV File with Headers?. For more information, please follow other related articles on the PHP Chinese website!