Easily read and write CSV files with the PHP5 SPL

Importing or exporting data in CSV format is a classic for a business application or a back office. Little known, the Standard PHP Library (SPL) makes it easy to manipulate files with the SplFileObject class. This class has specific functions for manipulating files in CSV format in reading and writing. So it's easy to write OOP style code and ditch old school procedural code for this kind of task.

1. Read a CSV file

Reading is simple, you just have to pass the file path to the constructor and the opening mode (here 'r') and then specify to the class that you want a CSV support.

$csv = new SplFileObject('upload_dir/file1.csv', 'r');
$csv->setFlags(SplFileObject::READ_CSV);
 

The SplFileObject class implements the Iterator interface of the SPL, it only takes a foreach loop to retrieve the rows one by one. Each row will be in the form of a table representing the columns in the CSV file.

foreach($csv as $ligne)
{
    echo 'value of first column: '.$ligne[0];
}
 

It is possible to configure the reading of the CSV file: the separation, framing or escape character. Here is the configuration for a CSV file generated with MS Excel.

$csv->setCsvControl(';', '"', '"');
 

Complete code for reading a CSV file from Excel:

$csv = new SplFileObject('upload_dir/file1.csv', 'r');
$csv->setFlags(SplFileObject::READ_CSV);
$csv->setCsvControl(';', '"', '"');
 
foreach($csv as $ligne)
{
    echo 'value of first column: '.$ligne[0];
}

2. Write a file

Creating and writing a CSV file is almost as easy as reading. Note the opening mode that differs.

$csv = new SplFileObject('upload_dir/file2.csv', 'w');
 

Since PHP version 5.4, the appearance of the fputcsv() method that allows you to convert a PHP array to CSV format and write it to the file. Each value in the table will be considered as a row in the CSV file. It is also possible to set the splitter and other options.

$people = [
  ['last_name', 'first_name', 'age'],
  ['Martin', 'Jean', '33'],
  ['Dupont', 'Guillaume', '28'],
  ['Dronz', 'Jay', '29'],
];
 
$csv = new SplFileObject('upload_dir/file2.csv', 'w');
$csv->fputcsv($personnes, ';');
 


As you may have noticed, at no time I attempt to close the resource like you do with fclose(). This task is managed internally. The icing on the cake, all errors related to the handling of files are thrown by Exceptions which makes object-oriented development even easier.

Add a comment