Convert CSV to JSON and JSON to CSV file format using PHP

Convert CSV to JSON and JSON to CSV file format using PHP

Share on Social Media

Convert CSV to JSON and JSON to CSV file format using PHP

Screenshots


Details


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:

nameauthorpublisherlanguage
Half GirlfriendChetan BhagatRupa Publicationsen
My Journey: Transforming Dreams into ActionsA.P.J. Abdul KalamRupa Publicationsen

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:

nameauthorpublisherlanguage
Half GirlfriendChetan BhagatRupa Publicationsen
My Journey: Transforming Dreams into ActionsA.P.J. Abdul KalamRupa Publicationsen

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"
}
]

Version History


1.0

Released On: March 15, 2018


Reviews


Not yet reviewed

Question or Comment


No support questions or comments