How to convert an array to CSV file in PHP ?

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.

Syntax :

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

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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);
?>

chevron_right


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.

Output in Microsoft Excel

Example 2: Suppose you want to put all the form inputs in a CSV file then first create a form to take input from the user and store it into an array. Then convert the array element into csv file.

index.html

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html> 
<html>
      
<head>
    <title>
        How to Convert Array to
        CSV file in PHP ?
    </title>
</head>
  
<body
          
    <!-- form tag to create form --> 
    <form action = "gfg.php" method = "post"
              
        Name <input type = "text" name = "name" /> 
                  
        <br><br
              
        Email <input type = "text" name = "email" /> 
                  
        <br><br>
              
        Phone <input type = "text" name = "phone" /> 
              
        <input type = "submit" name = "submit" value = "Submit"
    </form
</body>
  
</html>

chevron_right


gfg.php

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
$data = array(
    $_POST['name'],
    $_POST['email'],
    $_POST['phone']
);
  
// Open file in append mode
$fp = fopen('databse.csv', 'a');
  
// Append input data to the file  
fputcsv($fp, $data);
  
// close the file
fclose($fp);
?>

chevron_right



Output:

  • Input form:
  • Input data display in excel as output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.