Mave Mave - 6 months ago 10
JSON Question

How to convert a JSON file to a PHP file, with the PHP file containg a return []; for include()'ing?

The JSON file is about 15.000 lines, with a max nesting level of 7. A

json_decode()
takes between the 1.4 and 2.1 seconds, after about 15 checks. I've manually transformed the JSON file to a PHP file, with an additional array surrounding it, with a
return
in front of it. Reading and processing takes 0.03 seconds now.

Example JSON file:

{
"lvel1": {
"level2": {
"level3": [
1,
85151,
895151,
]
}
}
}


Desired PHP file:

return [
"lvel1" => [
"level2" => [
"level3" => [
1,
85151,
895151,
]
]
]
];


Is there easier way of doing this? Results have yielded nothing, as it always comes down to "converting JSON to Array PHP".

Answer
$json = '...';

$arr = json_decode($json, true);

$phpOutput = 'return ' . var_export($arr, true);