【发布时间】:2015-11-18 04:39:21
【问题描述】:
我正在编写一个 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 类型时,它们看起来确实正确。
【问题讨论】:
-
既然您使用的是 WordPress,那么当 WordPress 内置的配置选项有足够的支持时,为什么还要尝试以独特的方式做事(将配置写入文件并以 JSON 编码)并且易于管理?
-
这与配置 WordPress 无关——插件本身就是一个复杂的应用程序,我需要能够导出和导入数据。
标签: php json wordpress encoding utf-8