Home  >  Article  >  Backend Development  >  How to Convert a PHP Array to a Well-Formatted CSV File with Headers?

How to Convert a PHP Array to a Well-Formatted CSV File with Headers?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 18:58:30284browse

How to Convert a PHP Array to a Well-Formatted CSV File with Headers?

PHP Array Conversion to CSV: Streamlined Solution

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.

The Problem: Single-Line CSV and No Header

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.

Solution: Using fputcsv()

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.

Additional Notes

  • Use fopen('php://output', 'w') instead of hard-coding a filename to create the CSV in memory.
  • Set the appropriate headers for the CSV download in header().
  • Use fputcsv() to write the header row and subsequent rows of the CSV.
  • Close the file in the end with fclose().

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!

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