I have a php script , it accessing a json file by using file_get_contents()
, inside a json file, we have declared a php variable. Please let me know is there any w
It's not hard to interpolate this when you parse the structure first; you could then use array_walk() to iterate over each element in the array and change the value if it matches something that starts with $
:
$json=<<<'JSON'
{
"result":"$result",
"count":3
}
JSON;
// parse data structure (array)
$data = json_decode($json, true);
// define replacement context
$context = ['$result' => 'Hello'];
// iterate over each element
array_walk($data, function(&$value) use ($context) {
// match value against context
if (array_key_exists($value, $context)) {
// replace value with context
$value = $context[$value];
}
});
echo json_encode($data); // {"result":"Hello","count":3}
The obvious advantage is that you don't have to worry about escaping strings so that the JSON format is not violated.
If the data structure is recursive, you could use array_walk_recursive()
instead.