在WordPress插件中使用PHP代码编写UTF-8 JSON文件


Write UTF-8 JSON file from PHP code in WordPress plugin

我正在编写一个WordPress插件,需要能够编写和读取编码为JSON的复杂数据,可以包含UTF-8编码的文本。我在读取文件时遇到了问题(我得到了PHP解析错误),但我现在怀疑这是因为数据实际上没有编码为UTF-8(如我所料),而是编码为html编码的实体。

打开输出缓冲区并写入其中的函数看起来像这样——我错过了什么吗??

public function createUTFOutput($filename, $json)
{
        // Tells the browser to expect a json file and bring up the save dialog in the browser
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    if ($json)
        header('Content-Type: text/plain; charset=utf-8');
    else
        header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="'.$filename.'";');
        // This opens up the output buffer as a "file"
    $fp = fopen('php://output', 'w');
        // Hack to write as UTF-8 format
    fwrite($fp, pack("CCC",0xef,0xbb,0xbf));
    return $fp;
} // createUTFOutput()
    // PURPOSE: Write out data about Attribute $the_att to file $fp
public function write_att_data($fp, $the_att)
{
        // Create header to indicate Attribute record
    fwrite($fp, '{"type": "Attribute", "att-id": "'.$the_att->id.'", '."'n");
    fwrite($fp, '"att-privacy": "'.$the_att->privacy."'", 'n");
    fwrite($fp, '"att-def": '.$the_att->meta_def.", 'n");
    fwrite($fp, '"att-range": '.$the_att->meta_range.", 'n");
    fwrite($fp, '"att-legend": '.$the_att->meta_legend."'n}");
} // write_att_data()

是否需要一些其他设置,以便将文本写成文件的UTF-8字符,而不是HTML编码字符,就像在屏幕上显示一样?是否可能是输入过程以某种方式将UTF-8字符转换为html编码字符?当我查看存储在Mac上的mime类型文件时,它们看起来确实是正确的。

永远不要自己编写序列化函数。你的代码将不可避免地生成无效的JSON。

JSON,根据规范,是UTF-8。我想,如果您只是使用PHP的内置json_encode(),一切都会很好。

你的编码实体问题是由于WordPress的内置功能。我不知道如何重写它,但是以前有人这样做过。

对于那些面临同样问题的人来说,由于编码的不可预测和静默转换等原因,存在主要的复杂性。但是这个博客条目对我很有帮助:https://www.stefan-wallin.se/utf-8-issues-in-wordpress-with-update_post_meta-and-json_encode/

utf8_encode()函数可能会有所帮助。