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

时间:2015-06-29 04:21:47

标签: php json

我有一个php脚本,它使用file_get_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":"$result", "count":3 } 

但我需要像这样的输出

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

我无法访问json文件中的$result变量。 任何帮助Appreciated.Thanks

4 个答案:

答案 0 :(得分:13)

我可能会因此而被投票,但是可以在这种情况下使用吗?

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

答案 1 :(得分:9)

首先解析结构时插入这个并不困难;然后,您可以使用array_walk()迭代数组中的每个元素,如果它与以$开头的内容匹配,则更改该值:

$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格式。

如果数据结构是递归的,则可以改为使用array_walk_recursive()

答案 2 :(得分:2)

而不是按照{ "result":"$result", "count":3 }

的方式进行操作

我会这样做的。

我会为此

指定一个简短的变量代码

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

当我在PHP中获取JSON时,只需将其替换为我想要的PHP变量

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

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

答案 3 :(得分:-3)

<?php
$json = file_get_contents("test.json");
$json_a=json_decode($json,true);

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