How to create a CSV file for a user in PHP?

Spread the love

Sometimes, we want to create a CSV file for a user in PHP.

In this article, we’ll look at how to create a CSV file for a user in PHP.

How to create a CSV file for a user in PHP?

To create a CSV file for a user in PHP, we can use the fputcsv function.

For instance, we write

header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");

function output_csv($data)
{
    $output = fopen("php://output", "wb");
    foreach ($data as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}

output_csv([
    ["name 1", "age 1", "city 1"],
    ["name 2", "age 2", "city 2"],
    ["name 3", "age 3", "city 3"],
]);

to define the output_csvb function.

In it, we open the $output file with fopen.

Then we use a foreach loop to loop through $data.

In the loop, we call fputcsv with $output and $row to put $row in $output.

Then we call fclose to close the $output file.

We set the header to output CSV with header so CSV is returned.

Leave a Reply

Your email address will not be published.