pearl / csv-json-converter
Convert CSV to JSON and JSON to CSV file format using PHP
Installs: 5 322
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 1
Open Issues: 0
Requires
- php: ~7.0
Requires (Dev)
- phpunit/phpunit: ~5.0|~6.0
This package is auto-updated.
Last update: 2024-11-18 03:10:47 UTC
README
Convert CSV to JSON and JSON to CSV using PHP.
Installation
composer require pearl/csv-json-converter
How to use?
JSON to CSV:
Sample Json Data:
$jsonString = '[{ "name": "Half Girlfriend", "author": "Chetan Bhagat", "publisher": "Rupa Publications", "language": "en" }, { "name": "My Journey: Transforming Dreams into Actions", "author": "A.P.J. Abdul Kalam", "publisher": "Rupa Publications", "language": "en" }]';
use Pearl\CsvJsonConverter\Type\JsonToCsv;
Data loading:
- Array or Json values are accepted.
- Custom output header optional available. This is optional parameter if not passed then default header will be considered.
$jsonToCsv = new JsonToCsv($jsonString, ['headers' => ["productName", "author", "publisher", "lang"]]);
Or load the json data from file.
$jsonToCsv->load(__Dir__ . '/data/products.json');
Data conversion result options :
<!-- Convert and save the result to specificed path --> $jsonToCsv->convertAndSave(__Dir__ . '/output'); <!-- Convert and force download the file in browser--> $jsonToCsv->convertAndDownload(__Dir__ . '/output'); <!-- Convert and get data--> $jsonToCsv->convert();
Output:
CSV to JSON:
use Pearl\CsvJsonConverter\Type\CsvToJson;
Load the CSV data.
$csvToJson = new CsvToJson($csvString, ['bitmask' => 'JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES']);
Or Load the csv data from file.
$csvToJson->load(__Dir__ . '/data/products.csv');
Data conversion result options :
<!-- Convert and save to specificed path --> $csvToJson->convertAndSave(__Dir__ . '/output'); <!-- Convert and force download the file--> $csvToJson->convertAndDownload(__Dir__ . '/output'); <!-- Convert and get data--> $csvToJson->convert();
Sample Csv:
Output:
[{ "name": "Half Girlfriend", "author": "Chetan Bhagat", "publisher": "Rupa Publications", "language": "en" }, { "name": "My Journey: Transforming Dreams into Actions", "author": "A.P.J. Abdul Kalam", "publisher": "Rupa Publications", "language": "en" } ]