The League of Extraordinary Packages

Our Packages:

Presented by The League of Extraordinary Packages

Getting Started

Connections

Inserting Records

Selecting Records

Converting Records

Upgrading Guide

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

JSON conversion

JsonConverter converts a CSV records collection into a JSON string by implementing the Converter interface.

Settings

JsonConverter::options

<?php

public JsonConverter::options(int options): self

This method sets PHP’s json_encode optional flags.

Conversion

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

The JsonConverter::convert accepts an iterable which represents the records collection and returns a string.

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')
   ->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"
//     }
// ]

Tip: if needed you can use the Encoder object to correctly encode your CSV records before conversion.