Skip to content

Instantly share code, notes, and snippets.

@tzmfreedom
Last active August 17, 2023 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzmfreedom/43d2f1eb0bc2d59682699e37c28683dc to your computer and use it in GitHub Desktop.
Save tzmfreedom/43d2f1eb0bc2d59682699e37c28683dc to your computer and use it in GitHub Desktop.
converter json to var
<?php
// usage: echo '{json string}' | json2varexport.php
// @see https://gist.github.com/Bogdaan/ffa287f77568fcbb4cffa0082e954022
function varexport($expression, $return=FALSE) {
$export = var_export($expression, TRUE);
$export = preg_replace("/=> NULL/", '=> null', $export);
$export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
$array = preg_split("/\r\n|\n|\r/", $export);
$array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
$export = join(PHP_EOL, array_filter(["["] + $array));
if ((bool)$return) return $export; else echo $export;
}
$array = json_decode(file_get_contents('php://stdin'), true);
varexport($array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment