A simple How-To to csv handling with PHP

This How-To provides a quick overview on how to add simple csv import-export functionality to your PHP project.

Write a csv from an array


$data = array('Text1', 'Text2', 'Text3'); // start with your data array
$delimiter = ",";			  // set delimiting character
$file = "./target.csv";			  // specify the target file
$line[0] = implode($delimiter, $data);	  // set content of the first line
$fileprocess = fopen($file, "w");	  // open the target file in write mode
fwrite($fileprocess, $line[0]."\n");	  // write the first line to the file
fclose($fileprocess);			  // close the target file

Read a csv to an array


$delimiter = ",";			  // set delimiting character
$file = "./source.csv";			  // specify the source file
$line = file($file);			  // read file line by line
$data = explode($delimiter, $line[0]);	  // get contents by line
	  	  	  	  	  // (0 for line 1, 1 for line 2 and so on...)
// access the data
$data[0];
$data[1];
$data[2];

The structure of source.csv/target.csv


Text1,Text2,Text3

The scripts above are just to demonstrate the basic functionality. There are many possibilities to extend them (i.e. add a way to write more than one line by working with a “for” expression and so on…)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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