Skip to content

Instantly share code, notes, and snippets.

@bskiefer
Created May 3, 2024 19:48
Show Gist options
  • Save bskiefer/a91fbee399aa9b5a5db87291580b8cdb to your computer and use it in GitHub Desktop.
Save bskiefer/a91fbee399aa9b5a5db87291580b8cdb to your computer and use it in GitHub Desktop.
Convert JSON to PHP array output file syntax
<?php
$source = file_get_contents("readfile.json");
$target = sprintf("<?php\n\nreturn = %s", JSONToPHPArrayConverter::convert($source));
file_put_contents("output.php", $target);
class JSONToPHPArrayConverter
{
/**
* @param string $json
* @return string
* @throws \Exception - When string cannot be decoded to a PHP array due to invalid JSON
*/
public static function convert($json)
{
$array = json_decode($json, true);
if (is_null($array)) {
throw new \Exception('Invalid JSON');
}
return self::arrayToPHPSyntax($array);
}
/**
* @param array $array
* @return string
*/
private static function arrayToPHPSyntax(array $array)
{
$string = '[' . PHP_EOL;
foreach ($array as $key => $value) {
if (is_string($key)) {
$string .= ' ' . var_export($key, true) . ' => ';
}
if (is_array($value)) {
$string .= self::indent(self::arrayToPHPSyntax($value)) . ',' . PHP_EOL;
continue;
}
$string .= var_export($value, true) . ',' . PHP_EOL;
}
$string .= ']';
return $string;
}
/**
* @param string $string
* @return string
*/
private static function indent($string)
{
$lines = explode(PHP_EOL, $string);
$stringIndented = $lines[0] . PHP_EOL;
$lineCount = count($lines);
for ($i = 1; $i < $lineCount - 1; $i++) {
$stringIndented .= ' ' . $lines[ $i ] . PHP_EOL;
}
$stringIndented .= ' ' . $lines[ $lineCount - 1 ];
return $stringIndented;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment