How to save a JSON as unescaped UTF-8 in PHP 5.3?

前端 未结 5 1448
失恋的感觉
失恋的感觉 2020-12-10 19:40

I created a JSON file:

$json = array(
    \"Sample\" =>array(
        \"context\" => $context,
        \"date\"    => $date
    )
);

$url= \"sample         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-10 20:00

    If you can't use JSON_UNESCAPED_UNICODE, you could probably unescape the JSON yourself after it's been encoded:

    $json = array(
        'Sample' => array(
            'context' => 'جمهوری اسلامی ایران'
        )
    );
    
    $encoded = json_encode($json);
    var_dump($encoded); // context: "\u062c\u0645..."
    
    $unescaped = preg_replace_callback('/\\\\u(\w{4})/', function ($matches) {
        return html_entity_decode('&#x' . $matches[1] . ';', ENT_COMPAT, 'UTF-8');
    }, $encoded);
    
    var_dump($unescaped); // context is unescaped
    file_put_contents('sample.json', $unescaped);
    

    Here's an example in PHP5.3.

    However, this shouldn't be necessary, as any JSON parser should correctly parse the escaped Unicode characters and give you back your original string.

    EDIT: A better pattern to use might be /(?, which avoids incorrectly unescaping a JSON sequence like "\\u1234". See an example.

提交回复
热议问题