我有一个 php 脚本,它通过使用 file_get_contents()
访问一个 json 文件,在一个 json 文件中,我们声明了一个 php 变量。请让我知道有什么方法可以解析 json 文件中的 php 变量。
代码如下: 测试.json
{
"result":"$result",
"count":3
}
访问json文件的php脚本
<?php
$result = 'Hello';
$event = file_get_contents('test.json');
echo $event;
?>
现在输出如下:
{ "result":"$result", "count":3 }
但是我需要这样的输出
{ "result":"Hello", "count":3 }
我无法访问 json 文件中的 $result
变量。
任何帮助表示赞赏。谢谢
最佳答案
我可能会因此而被否决,但是在这种情况下可以使用 eval 吗?
<?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
}
关于php - 如何在 json 文件中插入现有的 php 字符串文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31107732/