Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set CsvEncoder delimiter in Symfony

I want to decode csv files, but some of them have ";" as delimiters which result in faulty objects. With the following code comma separated csv files are decoded properly:

https://symfony.com/blog/new-in-symfony-3-2-csv-and-yaml-encoders-for-serializer

// instantiation, when using it as a component
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

$serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);

// instantiation, when using it inside the Symfony framework
$serializer = $container->get('serializer');

// encoding contents in CSV format
$serializer->encode($data, 'csv');

// decoding CSV contents
$data = $serializer->decode(file_get_contents('data.csv'), 'csv');

I tried setting the context as parameter in the decode function:

$context = array(";", '"', "\\", ",");

$data = $serializer->decode(file_get_contents($file), 'csv', $context);

and as a parameter in the constructor:

$serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder($context)]);

Both tries without any different result.

I got it working this way:

$context = [
    CsvEncoder::DELIMITER_KEY => ';',
    CsvEncoder::ENCLOSURE_KEY => '"',
    CsvEncoder::ESCAPE_CHAR_KEY => '\\',
    CsvEncoder::KEY_SEPARATOR_KEY => ',',
];

$serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);
$serializer = $this->get('serializer');
$data = $serializer->decode(file_get_contents($file), 'csv', $context);
like image 553
Tristan Avatar asked Feb 07 '19 14:02

Tristan


2 Answers

For Symfony 4, the good syntax is :

$serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder()]);
$datas = $serializer->decode(file_get_contents($csvPath), 'csv', [CsvEncoder::DELIMITER_KEY => ';']);
like image 69
HypeR Avatar answered Sep 20 '22 06:09

HypeR


Try this:

$context = ['csv_delimiter' => [",", '"', "\\", "."] ];
like image 32
mary2501 Avatar answered Sep 19 '22 06:09

mary2501