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

前端 未结 4 1906
一生所求
一生所求 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:07
    <?php
    $json = file_get_contents("test.json");
    $json_a=json_decode($json,true);
    
    foreach ($json_a as $key => $value){
      echo  $key . ':' . $value;
    }
    ?>
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-13 03:25

    Instead of doing it your way like { "result":"$result", "count":3 }

    I would have done like this.

    I would have specified a short code for the variable for this

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

    and when I will get that JSON in PHP, just replace that with my desired PHP variable

    $event = file_get_contents('test.json');
    
    var $result = "hello";
    $parsed_json = str_replace("**result**",  $result,$event  ); 
    
    0 讨论(0)
  • 2021-02-13 03:28

    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
    }
    
    0 讨论(0)
提交回复
热议问题