Create csv file in php

We can create csv file in php by creating a proper string first, then put that content to a file. But there is another easy way to create csv file for your data using function fputcsv. Let you want to create a csv file from an array –

Let’s see you array is –

$data = array (

Its an one dimensional array, let we want to put first value to first line, second for the second line and so on. See the code below

$fp = fopen('data.csv', 'w');
foreach($data as $line){
 $val = explode(",",$line);
fputcsv($fp, $val);

On the first line, we created an empty file called data.csv, then we iterate $data array using foreach loop, created another array for each value of $data array, and passed the new array value $val to that file using fputscsv, so each time $val array value will be written on new line. That’s very simple.

One thought on “Create csv file in php

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.