pearl/csv-json-converter

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

1.0 2018-03-13 14:16 UTC

This package is auto-updated.

Last update: 2024-11-18 03:10:47 UTC


README

Build Status

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