Last active
June 10, 2025 13:58
-
-
Save ArnaudLigny/fbe791e05b93951ffc1f6abda8ee88f0 to your computer and use it in GitHub Desktop.
Convert PHP array to YAML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"require": { | |
"symfony/yaml": "^7.3" | |
} | |
} |
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
Exactly what I was looking for. Thanks for this.