Skip to content

Instantly share code, notes, and snippets.

@ArnaudLigny
Last active June 10, 2025 13:58
Show Gist options
  • Save ArnaudLigny/fbe791e05b93951ffc1f6abda8ee88f0 to your computer and use it in GitHub Desktop.
Save ArnaudLigny/fbe791e05b93951ffc1f6abda8ee88f0 to your computer and use it in GitHub Desktop.
Convert PHP array to YAML
#!/usr/local/bin/php
<?php
/*
* CLI to convert a PHP array to a YAML file.
*/
error_reporting(E_ALL ^ E_NOTICE);
date_default_timezone_set('UTC');
require_once 'vendor/autoload.php';
if (php_sapi_name() !== 'cli') {
echo "This script must be run from the command line.\n";
exit(1);
}
use Symfony\Component\Yaml\Yaml;
if (!isset($argv[1]) || $argv[1] == 'help') {
echo <<<EOT
Converts a PHP array to a YAML file.
Usage:
php array2yaml.php <input> [<output>]
Arguments:
input Input file name (required, string)
output Output file name (optional, string, default: <input>.yml)
EOT;
exit(0);
}
$input = (string) $argv[1];
$output = pathinfo($input)['filename'] . '.yml';
if (isset($argv[2])) {
$output = (string) $argv[2];
}
try {
is_file($input) or throw new \Exception("File \"$input\" does not exist");
$array = include($input);
file_put_contents($output, Yaml::dump($array, 99, 2));
echo "Success: file \"$output\" created\n";
exit(0);
} catch (\Exception $e) {
echo 'Error: ', $e->getMessage(), "\n";
exit(1);
}
{
"require": {
"symfony/yaml": "^7.3"
}
}
@yassinechabli
Copy link

nice try. thank you

@RyanNutt
Copy link

RyanNutt commented Jun 4, 2022

Exactly what I was looking for. Thanks for this.

@ArnaudLigny
Copy link
Author

Updated to symfony/yaml 7.3 + better CLI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment