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

前端 未结 4 1901
一生所求
一生所求 2021-02-13 02:39

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

4条回答
  •  庸人自扰
    2021-02-13 03:20

    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.

提交回复
热议问题