如何在PHP 5.3中将JSON保存为未转义的UTF-8? [英] How to save a JSON as unescaped UTF-8 in PHP 5.3?

查看:93
本文介绍了如何在PHP 5.3中将JSON保存为未转义的UTF-8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个JSON文件:

I created a JSON file:

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

$url= "sample.json";
$myfile = fopen($url, "w") or die("Unable to open file!");
fwrite($myfile, json_encode($json));    
fclose($myfile);

我需要将其另存为UTF-8,并且不能在PHP 5.3中使用JSON_UNESCAPED_UNICODE.那我现在该怎么办?

I need to save it as UTF-8 and I can't use JSON_UNESCAPED_UNICODE in PHP 5.3. So what should I do now?

推荐答案

如果您不能使用JSON_UNESCAPED_UNICODE,则可能会在对JSON进行编码后自行取消转义:

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);

这是PHP5.3中的示例.

Here's an example in PHP5.3.

但是,这不是必需的,因为任何JSON解析器都应正确解析转义的Unicode字符并把原始字符串还给您.

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

编辑:更好的模式可能是/(?<!\\\\)\\\\u(\w{4})/,这可以避免错误地转义JSON序列(如"\\u1234"). 查看示例.

EDIT: A better pattern to use might be /(?<!\\\\)\\\\u(\w{4})/, which avoids incorrectly unescaping a JSON sequence like "\\u1234". See an example.

这篇关于如何在PHP 5.3中将JSON保存为未转义的UTF-8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆