Home >Backend Development >PHP Tutorial >How to Create and Download CSV Files from PHP Scripts?

How to Create and Download CSV Files from PHP Scripts?

Susan Sarandon
Susan SarandonOriginal
2024-11-12 20:28:02274browse

How to Create and Download CSV Files from PHP Scripts?

Creating and Downloading CSV Files from PHP Scripts

Introduction

To enhance website functionality, you may encounter scenarios where you need to export data from your PHP arrays into CSV files for download by users. However, as a novice programmer, understanding how to execute this task can be challenging. This article offers a comprehensive guide to achieve this goal effectively.

Creating the CSV File

To generate the CSV file from your PHP array, you can utilize the built-in fputcsv() function:

$f = fopen("tmp.csv", "w");
foreach ($array as $line) {
    fputcsv($f, $line);
}

Configuring HTTP Headers

To trigger the "Save as" dialogue in browsers, you need to specify the appropriate HTTP headers:

header('Content-Disposition: attachment; filename="filename.csv"');

Combining Both Processes

By combining the CSV file creation and HTTP header configuration, you can generate the following function:

function array_to_csv_download($array, $filename = "export.csv", $delimiter = ";") {
    // Open file in memory
    $f = fopen('php://memory', 'w');
    
    // Generate CSV data
    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
    
    // Set headers
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    // Output file
    fpassthru($f);
}

Usage

To use this function, you can simply provide your PHP array and a filename:

array_to_csv_download(array(
    array(1, 2, 3, 4),
    array(1, 2, 3, 4)
), "numbers.csv");

Alternative Method

For improved performance, you can use php://output instead of php://memory and eliminate the seek operation:

function array_to_csv_download($array, $filename = "export.csv", $delimiter = ";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    
    // Open output stream
    $f = fopen('php://output', 'w');
    
    // Generate CSV data
    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
}

The above is the detailed content of How to Create and Download CSV Files from PHP Scripts?. 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