Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I interpolate an existing php string literal inside a json file?

Tags:

json

php

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 way to parse the php variable inside a json file.

Below is the code: test.json

{
    "result":"$result",
    "count":3
}

php script for accessing the json file

<?php
$result = 'Hello';
$event = file_get_contents('test.json');
echo $event;
?>

Now the output is like below:

{ "result":"$result", "count":3 } 

But I need the output like this

{ "result":"Hello", "count":3 } 

I'm not able to access the $result variable inside a json file. Any help Appreciated.Thanks

like image 507
Vipin Avatar asked Jun 29 '15 04:06

Vipin


1 Answers

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
}
like image 170
Dave Chen Avatar answered Oct 05 '22 22:10

Dave Chen