The League of Extraordinary Packages

Our Packages:

Presented by The League of Extraordinary Packages

Getting Started

Connections Settings

Inserting Records

Selecting Records

Interoperability

Converting Records

Upgrading Guide

This is the documentation for the upcoming version 9.0. This is a work in progress

JSON conversion

<?php

class JsonConverter
{
    public function options(int $options): self
    public function convert(iterable $records): string
}

JsonConverter converts a CSV records collection into a JSON string using PHP’s json_encode function.

Settings

<?php

public JsonConverter::options(int $options): self

The options methods sets PHP’s json_encode flag parameter.

By default, the flag parameter is set to 0.

Conversion

<?php
public JsonConverter::convert(iterable $records): string

The JsonConverter::convert accepts:

and returns a string.

Notice: To convert an iterator, iterator_to_array is used, which could lead to a performance penalty if you convert a large Iterator.

If a error occurs during the convertion an RuntimeException exception is thrown with additional information regarding the error.

<?php

use League\Csv\JsonConverter;
use League\Csv\Reader;

$csv = Reader::createFromPath('/path/to/file.csv', 'r');
$csv->setHeaderOffset(0);

$json = (new JsonConverter())
    ->options(JSON_PRETTY_PRINT)
    ->convert($csv)
;

echo '<pre>', $json, PHP_EOL;
// [
//     {
//         "firstname": "john",
//         "lastname": "doe",
//         "email": "john.doe@example.com"
//     },
//     {
//         "firstname": "jane",
//         "lastname": "doe",
//         "email": "jane.doe@example.com"
//     },
//     ...
//     {
//         "firstname": "san",
//         "lastname": "goku",
//         "email": "san.goku@dragon-ball.super"
//     }
// ]

If needed you can use the CharsetConverter object to correctly encode your CSV records before conversion.

<?php

use League\Csv\JsonConverter;
use League\Csv\CharsetConverter;
use League\Csv\Reader;

$csv = Reader::createFromPath('/path/to/file-in-iso-8859-15-format.csv', 'r');

$charset_converter = (new CharsetConverter())
    ->input_encoding('iso-8859-15')
    ->output_encoding('utf-8')
;

$data = $charset_converter->convert($csv);

$json = (new JsonConverter())
    ->convert($data)
;