How to create csv (comma-separated values) file using php?

Once I had a requirement to create csv file using php.
For that I used following sample code.
It will create / overwrite test.csv file, write heading row and content rows in csv file.

// Create csv file and open it for write
	$fname = 'test.csv';
	$fp = fopen($fname, 'w');

// Write heading row in csv file
	$heading_row = array('No', 'Name', 'Address', 'Mobile No');
	fputcsv($fp, $heading_row);

// Make array for csv row content and write it in file
	$content_row1 = array('1', 'ABC', 'Ahmedabad, India.', '9574021650');
	$content_row2 = array('2', 'PQR', 'Anand, India.', '9911546874');
	$content_row3 = array('3', 'XYZ', 'Akola, India.', '9574043210');
	$content_row4 = array('4', 'EFG', 'Delhi, India.', '9574054789');
	$content_row5 = array('5', 'LMN', 'Mumbai, India.', '9685741236');
	fputcsv($fp, $content_row1);
	fputcsv($fp, $content_row2);
	fputcsv($fp, $content_row3);
	fputcsv($fp, $content_row4);
	fputcsv($fp, $content_row5);

// Close csv file pointer

Hope this will help you….

Speak Your Mind

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

%d bloggers like this: