Home >Backend Development >PHP Tutorial >How to Resolve PHP Array to CSV Conversion Issues and Implement a Superior Approach
The goal of converting an array of products into a CSV file can be achieved effectively. However, there are nuances to address.
In your code, the main issue seems to lie in the use of multiple loops, which can lead to an undesirable single-line CSV output.
To overcome this, consider employing the built-in PHP function, fputcsv(). Here's an improved code snippet:
<code class="php">$sql = "SELECT id, name, description FROM products"; if ($result = $mysqli->query($sql)) { $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')); while ($p = $result->fetch_array()) { fputcsv($output, $p); } fclose($output) or die("Can't close php://output"); }</code>
In this revised approach:
Note: Remember to unlink() the file after creating it if you don't wish to store a copy on the server.
By implementing these changes, you can generate a well-formatted CSV file with headers and line breaks as expected.
The above is the detailed content of How to Resolve PHP Array to CSV Conversion Issues and Implement a Superior Approach. For more information, please follow other related articles on the PHP Chinese website!