DataMapper ORM


CSV Import and Export Methods (csv)

To enable these methods, add 'csv' to DataMapper's config, under 'extensions'.

Convert arrays of DataMapper models to and from CSV files. This extension uses the built-in PHP fgetcsv and fputcsv. Many issues with CSV formats can be resolved by checking the PHP manual.

csv_export($filename, $fields, $include_header)

Outputs the $fields within $object->all to a CSV file. If $object->all is an empty array, nothing is written and FALSE is returned.

Usage

$u = new User();
// load all users
$u->get();
// Output $u->all to /tmp/output.csv, using all database fields.
$u->csv_export('/tmp/output.csv');

csv_import($filename, $fields, $header_row, $callback)

Imports a CSV file into DataMapper objects.

Important: If the CSV file has an id column, you either need to exclude it from the list of fields, or use the save_as_new method.

Usage

function import_csv()
{
    // Save the CSV file, place the filename into $csvfile
    $n = new Note();
    // After each row is parsed, $this->_save_note will be called with the new Note.
    $saved_notes = $n->csv_import($csvfile, array('message'), TRUE, array($this, '_save_note'));
    echo "$saved_notes Notes were imported.";
}
function _save_note($note)
{
    if( ! $note->save())
    {
        echo($note->error->string);
        return FALSE;
    }
    return TRUE;
}