How to export to CSV via PHP?

Spread the love

Sometimes, we want to export to CSV via PHP.

In this article, we’ll look at how to export to CSV via PHP.

How to export to CSV via PHP?

To export to CSV via PHP, we can write an array itno a csv.

For instance, we write

$list = [
    ["aaa", "bbb", "ccc", "dddd"],
    ["123", "456", "789"],
    ['"aaa"', '"bbb"'],
];

$fp = fopen("file.csv", "w");

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

to create the $list array.

Then we call fopen to open the file.csv file with write permission.

Next, we use a foreach loop to loop through the $list.

In it, we call fputcsv to write the $fields row into the $fp file.

Then we call fclose to close the $fp file.

Conclusion

To export to CSV via PHP, we can write an array itno a csv.

Leave a Reply

Your email address will not be published.