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)
- $filename: The name of the file to save to, or an open handle. If this is a string, the file will be overwritten. If it is a handle, it will not be closed.
- $fields: (Optional) If provided, only these fields will be exported. If empty or not provided, all of the database columns will be exported.
- $include_header: (Optional) If TRUE, the column names will be output on the first row (recommended). Defaults to TRUE.
- Returns: TRUE or FALSE if an error occurs, or the array of objects is empty.
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)
- $filename: The name of the file to save to, or an open handle. If this is a string, the file will be overwritten. If it is a handle, it will not be closed.
- $fields: (Optional) If provided, only these fields will be imported. If empty or not provided, all of the database columns will be imported.
- $header_row: (Optional) If TRUE, the first row is assumed to be a header containing the field names. Defaults to TRUE.
- $callback: (Optional) A callback method for each row. The provided method will be called with the new object as the argument. The method should return FALSE if the item could not be imported, the string 'stop' to stop importing, or TRUE on success.
- Returns: If a callback method was specified, the number of successfully processed objects. Otherwise, an array containing the (unsaved) imported DataMapper objects.
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; }