Write array of data to the CSV file php

Write array of data to the CSV file php

To write data to the CSV file using PHP we can use native PHP functions.
In the example below we can see how to write an array of data to the CSV file using PHP for this array:

$dataToCSV = [
    ['1', 'First title',],
    ['2', 'Second title',],
    ['3', 'Third title',],
];

Let’s update our array by adding titles for each cell.

$dataToCSV = [
    ['1', 'First title',],
    ['2', 'Second title',],
    ['3', 'Third title',],
];

$titles = ['ID', 'Title'];
array_unshift($dataToCSV, $titles);

And write array data to the CSV file:

$dataToCSV = [
    ['1', 'First title',],
    ['2', 'Second title',],
    ['3', 'Third title',],
];

$titles = ['ID', 'Title'];

array_unshift($dataToCSV, $titles);

$fileName = 'data.csv';
$file = fopen($fileName, 'w');
foreach ($dataToCSV as $row) {
    fputcsv($file, $row);
}
fclose($file);

On the same level as your php file you will find data.csv file.

Leave a Reply

Your email address will not be published. Required fields are marked *