Simple PHP CSV Class

Throughout my years in programming I've dealt a lot with reading and importing CSV files, exporting queries into CSV files, and building dynamic CSV files. I decided it was time to create a simple PHP class to do all this work for me.

With this class you can change the terminator, separator, enclosed, and escaped characters as well as mime type. You decide the file name and there are simple built in functions to let you easily navigate the rows and columns of the CSV.

The class is compatible with newer AND older (less than 5.3.0) versions of PHP.

Download the PHP CSV Class from Bitbucket here.

Here are some examples of how to use the simple PHP CSV Class.

Reading a CSV File

include('class-CSV.php');
 
//Start the CSV object and provide a filename
$csv = new CSV("testfile");
$csv->readCSV("/home/example/public_html/files/test.csv");
 
//if the file had a header row you would use
//$csv->readCSV("/home/example/public_html/files/test.csv", true);
 
//access the data
$totalRows = $csv->totalRows();
$totalCols = $csv->totalCols();
for($row=0; $row<$totalRows; $row++) {
  for($col=0; $col<$totalCols; $col++) {
    $value = $csv->getRowCol($row, $col);
    echo 'Row: '.$row.' Col: '.$col.' Value: '.$value.'<br />';
  }  
}

Building and Adding to a CSV Object

include('class-CSV.php');
 
//Start the CSV object and provide a filename
$csv = new CSV("testfile");
 
//create the header row
$headerRow = array("ID", "NAME", "POSITION");
$csv->headerColumns($headerRow);
 
//add some data
$data = array(1, "John Doe", "Sales");
$csv->addRow($data);

Retrieving a Specific Row and Column Value

include('class-CSV.php');
 
//Start the CSV object and provide a filename
$csv = new CSV("testfile");
 
//create the header row
$headerRow = array("ID", "NAME", "POSITION");
$csv->headerColumns($headerRow);
 
//add some data
$data = array(1, "John Doe", "Sales");
$csv->addRow($data);
$dataTwo = array(2, "Bobby Bush", "Admin");
$csv->addRow($data);
 
//show the value of specific row and column
echo $csv->getRowCol(0, 1); //outputs "John Doe"
 
//show the value of specific row and column using header values
echo $csv->getRowCol(1, $csv->getHeaderIndex("NAME")); //outputs "Bobby Bush"

Exporting a CSV File

include('class-CSV.php');
 
//Start the CSV object and provide a filename
$csv = new CSV("testfile");
 
//create the header row
$headerRow = array("ID", "NAME", "POSITION");
$csv->headerColumns($headerRow);
 
//add some data
$data = array(1, "John Doe", "Sales");
$csv->addRow($data);
$dataTwo = array(2, "Bobby Bush", "Admin");
$csv->addRow($data);
 
//export the data to a CSV file
$csv->export();

Tags: