-
Notifications
You must be signed in to change notification settings - Fork 10
CSV
The CSV module allow you to read and write Comma Separated Value data.
You can open a CSV file with the CSV::open
factory. You can pass an optional separator or a format constant as a second parameter. Default value is auto-guessing of the separator.
$csv = CSV::open('mydata.csv')->each(function($row){
print_r($row);
});
With a CSV object in read-mode, the each
method will return all data if no parameters are passed to it.
$all_data = CSV::open('mydata.csv')->each();
With a CSV object in read-mode, the read
method will return a single row from the CSV file.
$my_data = CSV::open('mydata.csv');
$first_row = $my_data->read();
$second_row = $my_data->read();
You can create a CSV file with the CSV::create
factory. You can pass an optional separator or a format constant as a second parameter. Default value is CSV:STANDARD
, that is a comma ,
separated.
$csv = CSV::create('characters.csv');
With a CSV object in write-mode, the write
method will accept an array or an object and will write it to the CSV file.
The schema
method defines the headers of the table to be written (if omitted the first row keys are used instead).
When a schema is defined, every written row will be reordered and filtered to be coherent with it.
$csv = CSV::create('characters.csv');
$csv->schema(['name','surname','email']);
$csv->write([
'email' => '[email protected]',
'name' => 'Frank',
'surname' => 'Castle',
]);
$csv->write([
'name' => 'King',
'surname' => 'Pin',
'dirty' => 1234,
'email' => '[email protected]',
]);
echo $csv;
Returns:
name,surname,email
Frank,Castle,[email protected]
King,Pin,[email protected]
// Convert an unknown-CSV to an Excel compatible one.
CSV::open('agents.csv')->convert('agents.xls',CSV::EXCEL);
This is pratically a shorthand for:
$csv = CSV::create('agents.xls',CSV::EXCEL);
CSV::open('agents.csv')->each(function($row) use ($csv) {
$csv->write($row);
});
Core is maintained by using the Semantic Versioning Specification (SemVer).
Copyright 2014-2016 Caffeina srl under the MIT license.
http://caffeina.com