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);
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 => ';']);
Try this:
$context = ['csv_delimiter' => [",", '"', "\\", "."] ];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With