PHP

Array To CSV In PHP

We are here to discuss Array to CSV in PHP. CSV is the short form of Comma Separated Values File, a CSV is a file that contains array data in the form of a table, there will be no commas in the CSV file. The purpose of using a CSV file is to get the data of arrays free of commas.

A file will be created in which the commas-free array data will be stored in table form and it will be saved in your project directory, you can open that file in MS Excel file format.

Syntax

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

Parameters

There are 5 parameters in the above syntax, file and fields are the required parameters, and separator, enclosure, and escape are the optional ones.

Let’s see how it works.

Example 1

<?php
$arr =array(
    
array('a'=>"Peter", 'b'=>"18" ,'c'=>"[email protected]", 'd'=>"England"),
    
array('a'=>"Peter", 'b'=>"18" ,'c'=>"[email protected]", 'd'=>"England")
);
$fill = fopen("record.csv","w");
foreach ($arr as $line) {
  fputcsv($fill, $line);
}
fclose($fill);
?>

In the above code, we declared an associative array then we declared a variable in which we used a function for creating a CSV file, in parameters we pass the file name by which name we want to save the file so we name it as”recored.csv” for CSV file in which our array data will be store.

Then we used the “foreach” loop with the “fputcsv” function which will print the array data into a CSV file in table form you can see that file where you saved your existing PHP file and the CSV file will be open in MS Excel format.

Output

As you can see above this is the file that was created automatically in our project folder (record.csv)by just using the” fputcsv function” as you can see the associative array data is stored in the MS Excel file.

Example 2

<?php
$arr = array (
 
array("Peter", "18" ,"[email protected]", "England"),
 
array("John", "19", "[email protected]", "France"),
 
array("Noah", "20" ,"[email protected]", "UK"),
 
array("Scoob", "21" ,"[email protected]", "USA"),
 
array("Barber", "22" ,"[email protected]", "Autralia"),
 
array("Henry", "23" ,"[email protected]", "UK")
);
$file = fopen("contacts.csv","w");
foreach ($arr as $line) {
  fputcsv($file, $line);
}
fclose($file);
?>

In the above example, we declared a multidimensional array and then again used the open function for creating a CSV file, then we used the foreach loop with the fputcsv function let’s check the project folder.

Output

As you can see the contects.csv file has been created in the folder.

Conclusion

In this tutorial, we talk about CSV and how to convert an array in CSV in PHP then we discuss some examples.

Suggested Article:

Leave a Comment