Convert array to CSV and force download

Convert array to CSV and force download

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Convert Array to CSV and Force Download: A Practical Guide

You are encountering two distinct issues here: the data structure is being flattened into a single string before processing, and the headers are configured for an Excel file extension rather than a true CSV download. The code snippet you provided attempts to manually construct a CSV string and then pass that entire string to fputcsv, which fundamentally misunderstands how that function works.

When you iterate through your product array using SQL queries, you are building a single variable $data by concatenating strings together. However, $row is an associative or indexed array fetched from the database. If you concatenate these rows into one giant string like "$line .= $value", you lose the multidimensional structure required for CSV generation.

The function array_to_CSV receives this concatenated string as its first argument. When fputcsv executes on a single string instead of an array, it treats that entire string as the header row and writes it to a file with no subsequent rows. This explains why your output appears as "one long line." To fix this, you must pass an array of arrays to fputcsv, where the first element is the header column names and the subsequent elements are the data rows.

Furthermore, forcing a download relies on specific HTTP headers. Your current setup sets the filename extension to .xls (Excel binary) while setting the content type to application/octet-stream. While browsers will try to open this, modern applications expect .csv files with a text/csv MIME type. If you want the file to force a download rather than opening inline in the browser, ensure you are using the correct disposition and filename extension.

Here is a corrected approach that addresses both the data structure and the headers:

// Assume $prods contains an array of product IDs
$headers = ['id', 'name', 'price']; // Define your actual column names here

$csvData = [];

foreach ($prods as $productId) {
    // Use prepared statements to prevent SQL injection
    $stmt = $mysqli->prepare("SELECT id, name, price FROM products WHERE id = ?");
    $stmt->bind_param("i", $productId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        // Escape quotes and wrap fields in quotes for CSV compliance
        $csvRow = [];
        foreach ($headers as $col) {
            $val = $row[$col];
            // Replace double quotes with two double quotes per RFC 4180
            $val = str_replace('"', '""', $val); 
            $csvRow[] = '"' . $val . '"';
        }
        $csvData[] = implode(',', $csvRow);
    }
}

// Construct the full CSV content
if (!empty($csvData)) {
    // Add header row
    array_unshift($csvData, implode(',', array_map(function($h) { return '"' . $h . '"'; }, $headers)));
    
    $content = implode("\r\n", $csvData);
} else {
    $content = "(0) Records Found!\n";
}

// Set headers for CSV download
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=products.csv");
header("Pragma: no-cache");
header("Expires: 0");

// Output directly to browser without intermediate variable manipulation
echo $content;
exit();

The key change is constructing the CSV line-by-line using implode and passing the resulting array of strings to a standard output stream, or echoing them directly. In this example, we echo the data immediately after setting the headers, which is often cleaner than buffering into a variable and trying to pass it back through fputcsv.

Note that you must exit the script (exit();) immediately after sending the headers and content. If any subsequent code runs, PHP might try to send additional output or headers, causing conflicts or preventing the download from triggering correctly. Additionally, always use prepared statements when querying by ID to avoid SQL injection vulnerabilities.

If you are working within a Laravel project, consider using the Faker package or similar utilities for generating test data, but for production exports, stick to raw database queries with proper escaping. For more complex export needs, libraries like spatie/laravel-excel handle formatting and bulk downloads efficiently without manual header manipulation.

Our network