How to Create and Download CSV Files from PHP Scripts?

Susan Sarandon
Release: 2024-11-12 20:28:02
Original
222 people have browsed it

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);
}
Copy after login

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"');
Copy after login

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);
}
Copy after login

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");
Copy after login

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);
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template