Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
pearlkrishn committed Mar 13, 2018
0 parents commit 1c12dfd
Show file tree
Hide file tree
Showing 12 changed files with 631 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
language: php

php:
- 7.0
- 7.1
- 7.2

sudo: false

before_script:
- travis_retry composer self-update
- travis_retry composer update ${COMPOSER_FLAGS} --no-interaction --prefer-source

script:
- vendor/bin/phpunit tests/ --stderr
21 changes: 21 additions & 0 deletions License
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2018 Pearlkrishn

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
110 changes: 110 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
[![Build Status](https://travis-ci.org/pearlkrishn/csv-json-converter.svg?branch=master)](https://travis-ci.org/pearlkrishn/csv-json-converter)

# 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:
```php
$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"
}]';
```

```php
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.

```php
$jsonToCsv = new JsonToCsv($jsonString, ['headers' => ["productName", "author", "publisher", "lang"]]);
```
Or load the json data from file.

```php
$jsonToCsv->load(__Dir__ . '/data/products.json');
```
##### Data conversion result options :
```php
<!-- 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:
| name | author | publisher | language |
| ------------ | ------------ | ------------ | ------------ |
| Half Girlfriend | Chetan Bhagat | Rupa Publications | en |
| My Journey: Transforming Dreams into Actions | A.P.J. Abdul Kalam | Rupa Publications | en |

### CSV to JSON:

```php
use Pearl\CsvJsonConverter\Type\CsvToJson;
```
Load the CSV data.
```php
$csvToJson = new CsvToJson($csvString, ['bitmask' => 'JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES']);
```
Or Load the csv data from file.
```php
$csvToJson->load(__Dir__ . '/data/products.csv');
```
##### Data conversion result options :
```php
<!-- 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:

| name | author | publisher | language |
| ------------ | ------------ | ------------ | ------------ |
| Half Girlfriend | Chetan Bhagat | Rupa Publications | en |
| My Journey: Transforming Dreams into Actions | A.P.J. Abdul Kalam | Rupa Publications | en |

#### Output:
```json
[{
"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"
}
]
```
31 changes: 31 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "pearl/csv-json-converter",
"description": "Convert CSV to JSON and JSON to CSV file format using PHP",
"type": "library",
"keywords": ["json", "csv", "json to csv", "csv to json", "php", "data converter"],
"authors": [
{
"name": "pearlkrishn",
"email": "[email protected]"
}
],
"require": {
"php" : "~7.0"
},
"require-dev": {
"phpunit/phpunit" : "~5.0|~6.0"
},
"license": "MIT",
"autoload": {
"psr-4": {
"Pearl\\CsvJsonConverter\\": "src/"
}
},
"autoload-dev": {
"psr-4": { "Pearl\\CsvJsonConverter\\Tests\\": "tests" }
},
"scripts" : {
"test" : "vendor/bin/phpunit tests/ --stderr"
},
"minimum-stability": "dev"
}
13 changes: 13 additions & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" stderr="true" backupGlobals="false" backupStaticAttributes="false" colors="true" verbose="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false">
<testsuites>
<testsuite name="Json Csv Converter PHP Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
</phpunit>
117 changes: 117 additions & 0 deletions src/ConverterAbstract.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php

namespace Pearl\CsvJsonConverter;

abstract class ConverterAbstract
{
/**
* Raw data.
*
* @var array
*/
protected $data;

/**
* Data Transformation options.
*
* @var array
*/
protected $options;

/**
* conversion details.
*
* @var array
*/
protected $conversion;

/**
* Downloadable filename.
*
* @var string
*/
protected $fileName;

/**
* Constructor.
*
* @param string $data
*/

public function __construct($data = null, array $options = [])
{
if (!is_null($data))
$this->setData($data);
$this->fileName = time();
$this->options = $options;
}

/**
* Load the data from file.
*
* @param string $filePath
* @return $this
*/

public function load($filePath)
{
$this->fileName = pathinfo($filePath, PATHINFO_FILENAME);
$this->setData(file_get_contents($filePath));

return $this;
}

/**
* Get the file name.
*
* @return string
*/

public function getFileName() : string
{
return $this->fileName;
}

/**
* Get the data.
*
* @return array
*/

public function getData() : array
{
return $this->data;
}

/**
* @param null $fileName
* @param bool $exit
*/

public function convertAndDownload($fileName = null, $exit = true)
{
header('Content-disposition: attachment; filename=' . ($fileName ?? $this->fileName) . '.' . $this->conversion['extension']);
header('Content-type: ' . $this->conversion['type']);
echo $this->convert();

if ($exit === true) {
exit();
}
}

/**
* @param string $path
*
* @return bool|int
*/
public function convertAndSave($path) : int
{
$fileFullPath = sprintf('%s.%s', $path, $this->conversion['extension']);

return file_put_contents($fileFullPath, $this->convert());
}

abstract public function convert();

abstract protected function setData($data);
}
61 changes: 61 additions & 0 deletions src/Type/CsvToJson.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace Pearl\CsvJsonConverter\Type;

use Pearl\CsvJsonConverter\ConverterAbstract;

class CsvToJson extends ConverterAbstract
{
/**
* Constructor.
*
* @param string $data
* @param array $options
*/

public function __construct($data = null, array $options = [])
{
parent::__construct($data, $options);
$this->conversion = [
'extension' => 'json',
'type' => 'application/json',
'delimiter' => ',',
'enclosure' => '"',
'escape' => '\\'
];
}

/**
* Convert the csv to array.
*
* @param string $data
* @return void
*/

protected function setData($data)
{
$this->data = array_filter(explode(PHP_EOL, $data));
}

/**
* Convert the csv to json.
*
* @return string|\Exception
*/

public function convert()
{
if (empty($this->data) === false && is_array($this->data)) {
$bitmask = empty($this->options['bitmask']) === false ? $this->options['bitmask'] : 0;
$keys = str_getcsv(array_shift($this->data), $this->conversion['delimiter'], $this->conversion['enclosure'], $this->conversion['escape']);

foreach ($this->data as $key => $values) {
$result[] = array_combine($keys, str_getcsv($values, $this->conversion['delimiter'], $this->conversion['enclosure'], $this->conversion['escape']));
}

return json_encode($result, $bitmask);
} else {
throw new \Exception("Invalid data given");
}
}
}
Loading

0 comments on commit 1c12dfd

Please sign in to comment.