如何在json文件中插入现有的php字符串文字?

如何在json文件中插入现有的php字符串文字?,php,json,Php,Json,我有一个php脚本,它使用file\u get\u contents()访问json文件,在json文件中,我们声明了一个php变量。请让我知道是否有任何方法可以解析json文件中的php变量 代码如下: test.json { "result":"$result", "count":3 } 用于访问json文件的php脚本 <?php $result = 'Hello'; $event = file_get_contents('test.json'); echo $ev

我有一个php脚本,它使用
file\u get\u contents()
访问json文件,在json文件中,我们声明了一个php变量。请让我知道是否有任何方法可以解析json文件中的php变量

代码如下: test.json

{
    "result":"$result",
    "count":3
}
用于访问json文件的php脚本

<?php
$result = 'Hello';
$event = file_get_contents('test.json');
echo $event;
?>
但我需要这样的输出

{ "result":"Hello", "count":3 } 
我无法访问json文件中的
$result
变量。 感谢您的帮助。谢谢
<?php
$json = file_get_contents("test.json");
$json_a=json_decode($json,true);

foreach ($json_a as $key => $value){
  echo  $key . ':' . $value;
}
?>

我可能会因此被否决,但在这种情况下可以使用eval吗

<?php

$json = '{
    "result":"$result",
    "count":3
}'; //replace with file_get_contents("test.json");

$result = 'Hello world';



$test = eval('return "' . addslashes($json) . '";');
echo $test;

而不是像
{“result”:“$result”,“count”:3}

我会这样做的

我会为此变量指定一个简短的代码

{“结果”:“**结果**”,“计数”:3}

当我在PHP中获得JSON时,用我想要的PHP变量替换它

$event = file_get_contents('test.json');

var $result = "hello";
$parsed_json = str_replace("**result**",  $result,$event  ); 

当您首先解析结构时,不难对其进行插值;然后,您可以使用来迭代数组中的每个元素,并在其与以
$
开头的内容匹配时更改值:

$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}

$json=访问
$result
变量是什么意思?!请提供你想要的样品。我刚刚在谷歌上搜索了你的查询,我找到了这个。不确定,但您可能会得到一些帮助您的问题实际上是“如何插入现有字符串文字?”或类似的问题不要忘记对
$result
字符串进行JSON转义!这是目前我唯一能想到的well@Phil要么就是这样,要么制定自己的解析方案(这比eval IMO好得多)。请记住,PHP将插入所有以
$
开头的内容,结果可能不再是有效的JSON。
$event = file_get_contents('test.json');

var $result = "hello";
$parsed_json = str_replace("**result**",  $result,$event  ); 
$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}