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
<?php
$json = file_get_contents("test.json");
$json_a=json_decode($json,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
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.
Instead of doing it your way like { "result":"$result", "count":3 }
I would have done like this.
I would have specified a short code for the variable for this
{ "result":"**result**", "count":3 }
and when I will get that JSON in PHP, just replace that with my desired PHP variable
$event = file_get_contents('test.json');
var $result = "hello";
$parsed_json = str_replace("**result**", $result,$event );
I might get downvoted for this, but could eval be used in this situation?
<?php
$json = '{
"result":"$result",
"count":3
}'; //replace with file_get_contents("test.json");
$result = 'Hello world';
$test = eval('return "' . addslashes($json) . '";');
echo $test;
Output:
{
"result":"Hello world",
"count":3
}