How to convert an array to CSV file in PHP?

Configurare noua (How To)

Situatie

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file. The file which has to be read and the fields are sent as parameters to the fputcsv() function and it returns the length of the written string on success or FALSE on failure.

Solutie

Pasi de urmat

Syntax : fputcsv( file, fields, separator, enclosure, escape )

 

<?php
// Create an array of elements
$list = array(
[‘Name’, ‘age’, ‘Gender’],
[‘Bob’, 20, ‘Male’],
[‘John’, 25, ‘Male’],
[‘Jessica’, 30, ‘Female’]
);
// Open a file in write mode (‘w’)
$fp = fopen(‘persons.csv’, ‘w’);
// Loop through file pointer and a line
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>

After running the above PHP program you can find a file named persons.csv in the same directory where the program file is located. When you open this file with a CSV file reader application like Microsoft Excel you’ll see the contents as shown in the below image.

Tip solutie

Permanent

Voteaza

(9 din 15 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?