PHP client to parse CSV data from a path, file, stream, resource or string into indexed or associative arrays.
PHP support updated to 7+
Install using composer
#composer.json
{
"require": {
"jabranr/csv-parser": "^3.0"
}
}
Run following to install
$ comsposer install
Initiate a new instance
$csv = new Jabran\CSV_Parser();
If you have composer
installed globally then:
Run unit tests
$ cd path/to/csv-parser
$ composer run tests
If you have phpunit
installed globally then:
$ cd path/to/csv-parser
$ phpunit
Get data from a string
/* @param: string $str */
$csv->fromString($str);
Get data from a resource (Since v2.0.2)
/* @param: resource $resource (f.e. resource created using fopen()) */
$csv->fromResource($resource);
Get data from a path/URL (Since v2.0.2)
/* @param: string $path */
$csv->fromPath($path);
Parse data for output
/**
* Set $headers true/false to include top/first row
* and output an associative array
*
* @param: boolean $headers (Default: true)
* @return: array
*/
$csv->parse($headers);
More useful methods (Since v2.0.2)
/**
* Set columns
* @param array $columns
* @return Jabran\CSV_Parser
*/
$csv->setColumns($columns);
/**
* Set rows
* @param array $rows
* @return Jabran\CSV_Parser
*/
$csv->setRows($rows);
/**
* Set headers
* @param array $headers
* @return Jabran\CSV_Parser
*/
$csv->setHeaders($headers);
/**
* Get columns
* @return array
*/
$csv->getColumns();
/**
* Get rows
* @return array
*/
$csv->getRows();
/**
* Get headers
* @return array
*/
$csv->getHeaders();
Example input string
require 'path/to/vendor/autoload.php';
$csv = new Jabran\CSV_Parser;
$str = 'id,first_name,last_name;1,Jabran,Rafique';
$csv->fromString($str);
// Output with headers:
$csv->parse();
Array(
[id] => 1,
[first_name] => 'Jabran',
[last_name] => 'Rafique'
)
// Output without headers:
$csv->parse(false);
Array(
[0] => array(
[0] => 'id',
[1] => 'first_name',
[2] => 'last_name'
),
[1] => array(
[0] => 1,
[1] => 'Jabran',
[2] => 'Rafique'
)
)
© 2015 onwards
MIT License - Jabran Rafique