Sort YAML file keys alphabetically

Published on 2021-08-15 • Modified on 2021-08-15

In this snippet, we see how to sort YAML file keys alphabetically with the YAML component. This is something that can be useful to normalize YAML i18n files. Be careful that constants are replaced by their actual values (thanks to the Yaml::PARSE_CONSTANT flag), and comments are lost. One other cron is that quotes are normalized, so you don't mix of single, double or not quote at all! 🌈


$yamlFile = $this->getParameter('kernel.project_dir'). '/translations/search/search.en.yaml';
$yamlContent = Yaml::parseFile($yamlFile, Yaml::PARSE_CONSTANT);
ksort($yamlContent, SORT_NATURAL);
$yamlNewContent = Yaml::dump($yamlContent);
file_put_contents($yamlFile, $yamlNewContent);

 More on Stackoverflow   Read the doc  Random snippet

  Work with me!