How to create and download a csv file from php script?

How to create and download a csv file from php script?

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

Stefan Bogdanescu

Founder & Senior Architect

Generating and Downloading CSV Files from a PHP Script

Turning a PHP array into a downloadable CSV file is a common requirement when exporting data for users to analyze in spreadsheet software. The approach depends entirely on how much control you need over the output format and whether you are using a framework like Laravel or raw PHP.

Server-Side Generation with fputcsv

For most straightforward scenarios, the built-in PHP function fputcsv() is the most efficient solution. It handles the complex logic of escaping commas within strings and managing row breaks automatically. This keeps your codebase clean without relying on external libraries.

To make the file downloadable, you must manipulate the HTTP headers before sending any output. You need to tell the browser that the response is a CSV file and suggest a filename. If you omit these headers, the browser will likely display the content as text or save it with a generic name like download.

Here is how you can implement this using your specific array structure:

$data = [
    [
        'fs_id' => '4c524d8abfc6ef3b201f489c',
        'name' => 'restaurant',
        'lat' => '40.702692',
        'lng' => '-74.012869',
        'address' => 'new york',
        'postalCode' => '',
        'city' => 'NEW YORK',
        'state' => 'ny',
        'business_type' => 'BBQ Joint',
        'url' => ''
    ]
];

// Set headers for CSV download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="restaurants.csv"');

// Create a file pointer for output
$output = fopen('php://output', 'w');

// Add the header row with keys from the first element
fputcsv($output, array_keys($data[0]));

// Write each row of data
foreach ($data as $row) {
    fputcsv($output, $row);
}

fclose($output);

In this example, array_keys($data[0]) is crucial because it dynamically generates the header row based on your associative array's keys. If you hardcode headers, you risk a mismatch if your data structure changes. The Content-Disposition: attachment directive ensures the browser prompts the user to save the file rather than trying to render it inline.

Handling Multi-Dimensional Arrays

Your source data is an indexed array of associative arrays. This nested structure works perfectly with fputcsv as long as every element in the outer array has keys matching the header row. However, if your dataset contains rows where a key is missing or null, fputcsv will write an empty value for that column. This preserves the column alignment but might require downstream validation if you are expecting specific data types like integers for IDs.

Using Laravel Collections

If your project is built with Laravel, you can leverage the collection helper methods to streamline this process. The toArray() method converts a collection back into a standard PHP array, which can then be passed directly into the file generation logic mentioned above. Alternatively, you can use the csv method if you are using packages like phpoffice/phpspreadsheet, though those add significant weight to your dependencies.

For lightweight Laravel projects, sticking to the native fputcsv approach avoids pulling in heavy spreadsheet libraries just for export functionality. You can encapsulate this logic into a controller action or a service class that returns a response with the appropriate headers set automatically using Laravel's response()->download() method. This pattern keeps your routes clean and separates concerns between data fetching and file delivery.

Security Considerations

When implementing dynamic CSV exports, always sanitize any user input that might be included in the filename or the file content. If you allow users to specify a custom filename, ensure they cannot inject path traversal sequences like ../../etc/passwd. Limit the filename to alphanumeric characters and standard punctuation. Furthermore, if you are exporting data from a database, ensure your queries are parameterized to prevent SQL injection before converting the result set into a CSV.

Performance at Scale

The method shown above streams the output directly to the browser using php://output. This is memory efficient because it does not load the entire file into RAM before sending it. However, if you are exporting hundreds of thousands of records, consider processing the data in chunks or utilizing background jobs to handle long-running exports without timing out your request. For large datasets, generating the file on disk first and then serving it from a temporary location can also provide better control over memory usage during the generation phase.

Our network