My favorites | Sign in
Project Logo
                
Search
for
Updated Sep 08, 2008 by Luke.Visinoni
Labels: Phase-Implementation
Documentation  
Library Documentation

NOTICE: This is old documentation. Please refer to the documentation here for more up-to-date information.

Introduction

PHP CSV Utilities provides an object-oriented interface to read, write, and detect the format of just about any type of csv file. It is written for PHP5 and I have no plans of writing a PHP4 version. I have only tested it on version 5.2.3. I will test it on other versions as soon as I can.

I am working on documenting every feature of this library, but it may take me a little while. Alright, enough talk, let's get to the library.

Classes

Csv_Reader

Csv_Reader is a simple interface to read a csv-formatted file. To use it, you simply pass the csv file name to its constructor.

$reader = new Csv_Reader('./data/orders.csv');

If the file you pass it doesn't exist, it will throw a Csv_Exception_FileNotFound exception. So it is recommended that you do something more like this to instantiate the object:

try {
    $reader = new Csv_Reader('./data/orders.csv');
} catch (Csv_Exception_FileNotFound $e) {
    echo "<p class='error'>File could not be found</p>";
}

I'm going to leave out the try / catch blocks in the rest of the documentation though for brevity.

getPath()

If, for any reason you need to retrieve the filename later on, you can use getPath() to do so. It will return the full path to the file it is reading, whether you used relative paths or not.

$reader = new Csv_Reader('./data/customers.csv');
print $reader->getPath(); // outputs something like /var/www/data/customers.csv

Loop through a csv file

Since Csv_Reader implements SPL's Iterator interface, you can actually loop through the csv file line by line with foreach.

$reader = new Csv_Reader('./data/orders.csv');
foreach ($reader as $row) {
    list($orderid, $orderdate, $customername) = $row;
    // do something with data here
}

Sexy, eh?

getRow()

If you prefer a while loop, you may use the getRow() method. It returns the current row and advances the internal pointer forward. If it reaches the end of the file, it will return false.

while ($row = $reader->getRow()) {
    // do something with row here
}

As of right now, this is also the best way to retrieve a header row. You cannot do this with foreach because it starts from the beginning and works through the entire file. getRow() starts from wherever you left it. This way you can grab the first row, then loop through the rest with a while loop. Eventually I may add some type of built-in getHeader() method or something, but I haven't decided yet.

$reader = new Csv_Reader("./data/products.csv");
$header = $reader->getRow();
while ($row = $reader->getRow()) { // starts from second row
    // do something with $row
}

current()

Returns the current row in the csv file, but does not advance the internal pointer forward. You could use this for a while loop as well, but it's not as convenient as the above two methods because you'd have to call next() inside the loop to advance the pointer.

while ($row = $reader->current()) {
    // do something with $row
    $reader->next(); // advances the internal pointer
}

key()

To find out what the reader is currently on, you can use key(). This is most useful while looping through the reader, but you can use it any time.

while ($row = $reader->getRow()) {
    print "We are on line #" . $reader->key() . "<br>"; 
}

rewind()

If you need to loop through a csv file more than once for any reason, you'll need to remember to rewind the object before trying to loop through a second time. I'm looking into ways I could avoid this inconvenience, but for now just be kind and rewind.

while ($row = $reader->getRow()) continue;
while ($row = $reader->getRow()) {
    // this code will never be executed because you didn't rewind!
}
$reader->rewind();
while ($row = $reader->getRow()) {
    // this code will be executed because you rewound!
}

Convert csv file to an array

toArray()

Csv_Reader is designed to only read a csv file a line at a time, but it is possible to get a two-dimensional array with every row of csv file in it.

$reader = new Csv_Reader('./data/orders.csv');
$orders = $reader->toArray();

Count rows in a csv file

count()

This class also implement SPL's Countable interface so you can count() reader to find out how many rows are there or you can call $reader->count(). Either is valid.

echo count($reader);
echo $reader->count();

Csv_Writer

An interface to write to a csv file. To use it, you pass a filename to its constructor. If the file doesn't exist, it will be created for you (although the constructor doesn't actually create the file, the close() method does. See that method below).

$writer = new Csv_Writer('./data/orders.csv');

getPath()

Csv_Writer, like Csv_Reader, has a getPath() method if you need to figure out what file you're writing to for any reason. Also like Csv_Reader, it will return the full path to the file, whether you passed in a relative path or not.

Writing to a csv file

There are several methods of writing to a csv file. It is important that you know that the file won't be written until the close() method is called. It is called automatically at the end of the script (or if you delete the writer) because close() is called in the destruct method. If you want your changes written right away, call the close() method after you are done writing. This will likely change in the next version. In version 0.3, writeRow() and writeRows() will write immediately instead of waiting until the close() method is called.

writeRow(array $data)

If you have an array of data you need to write to the csv file as the next row, you can use this method. To use it, simply call it with your array as its argument.

$row = array('234', 'Barney Rubble', '1135 Bedrock Blvd.', '09/16/3029 BC');
$writer->writeRow($row);

writeRows(mixed $data)

If you have several rows of data you want to write to the file, you may use writeRows() to do so. To use this method, call it with your (two-dimensional) array as its argument. It will loop through your array and write each row to the csv file. As with writeRow(), your data will not be written until you call the close() method or the script ends. See above for more info on why.

$data = get_orders(); // made up function
$writer->writeRows($data);

You can also pass writeRows() a reader object if you like. While this may not seem especially useful right now, once we get to the Csv_Dialect class, you will see why it is.

$reader = new Csv_Reader('./data/orders.csv');
$writer = new Csv_Writer('./data/neworders.csv');
$writer->writeRows($reader);
$writer->close();

close()

This method is called automatically by Csv_Writer's destruct method, but you may call it if you would like to write the data immediately.

Csv_Dialect

Csv_Dialect represents the format of a csv file. It has several parameters

By default, both reader and writer use a standard Csv_Dialect with the following parameters:

If you need to read or write a csv file with different parameters than this, you may provide a Csv_Dialect object to Csv_Reader or Csv_Writer as a second parameter. The library comes with a Csv_Dialect_Excel class which will read and write csv files in the same format as excel.

Examples of Csv_Dialect use

// make reader read excel files
$reader = new Csv_Reader('./data/orders.csv', new Csv_Dialect_Excel()); 
// make writer write csv files in excel format
$writer = new Csv_Writer('./data/orders.csv', new Csv_Dialect_Excel());

To create your own dialects, you may either subclass the Csv_Dialect class or you can provide custom parameters in the constructor.

Subclass

class Csv_Dialect_MyDialect extends Csv_Dialect
{
    public $quotechar = "'";
    public $escapechar = '"';
    public $lineterminator = "\n";
}
$reader = new Csv_Reader('./data/orders.csv', new Csv_Dialect_MyDialect());

Options Parameter

$dialect = new Csv_Dialect(array('quotechar' => "'", 'escapechar' => '"', 'lineterminator' => "\n"));
$reader = new Csv_Writer('./data/orders.csv', $dialect);


Sign in to add a comment
Hosted by Google Code