Home  >  Article  >  Backend Development  >  How to Resolve PHP Array to CSV Conversion Issues and Implement a Superior Approach

How to Resolve PHP Array to CSV Conversion Issues and Implement a Superior Approach

Linda Hamilton
Linda HamiltonOriginal
2024-10-19 19:02:30217browse

How to Resolve PHP Array to CSV Conversion Issues and Implement a Superior Approach

PHP Array to CSV: Troubleshooting and 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.

A Better Solution

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:

  • fputcsv() writes a line to the CSV file, taking an array as input.
  • The loop iterates over each row, writing them to the CSV.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn