8

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);

2 Answers 2

9

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 => ';']);
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$context = ['csv_delimiter' => [",", '"', "\\", "."] ];

1 Comment

The new version of the encoder now requires multiple context keys, as shown in other answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.