【问题标题】:Invalid Encoding json (problem when displaying Cyrillic)Invalid Encoding json(显示西里尔字母时出现问题)
【发布时间】:2019-06-18 06:07:45
【问题描述】:

我试图从表格中推断出一个文件,显示西里尔文时出现问题

PHP (7.1)

<?php
    header("Content-type: application/json; charset=utf-8");
    file_put_contents('export.json', json_encode($_REQUEST) );
?>

输出 You_name 字段是用字符编写的。

{"Entry_ID":"71","You_name":"\u041a\u043e\u0437\u043b\u0430\u043d\u0431\u0435\u043a \u0410\u043c\u0438\u0440 \u041f\u043e\u043c\u0438\u0434\u043e\u0440\u043e\u0432\u0438\u0447","You_phone":"7 (902) 998 1019","You_date":"19\/06\/2019"}

【问题讨论】:

  • 我觉得很合适。读取文件时需要用到json_decode。

标签: php json


【解决方案1】:

6 岁的答案仍然有效:Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

json_encode( $text, JSON_UNESCAPED_UNICODE );

例子:

/tmp $ cat test.php
<?php
echo json_encode(['key'=>'ыфва']), PHP_EOL;
echo json_encode(['key'=>'ыфва'], JSON_UNESCAPED_UNICODE), PHP_EOL;
/tmp $ php test.php
{"key":"\u044b\u0444\u0432\u0430"}
{"key":"ыфва"}
/tmp $ php --version
PHP 7.3.6 (cli) (built: May 31 2019 23:38:25) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.6, Copyright (c) 1998-2018 Zend Technologies
    with Xdebug v2.7.2, Copyright (c) 2002-2019, by Derick Rethans
    with Zend OPcache v7.3.6, Copyright (c) 1999-2018, by Zend Technologies

【讨论】:

  • 我正在尝试 PHP (7.1),PHP/5.4.0 的 6 岁答案
【解决方案2】:

您应该使用 $_POST 来获取如下表单数据

  header("Content-type: application/json; charset=utf-8");

  file_put_contents('export.json', json_encode($_POST) );

【讨论】:

  • 我试过 $_POST,但仍然没有显示西里尔字母...还有 iconv('utf-8', 'windows-1251', $str)
  • ... 和 file_put_contents('export.json', iconv('utf-8', 'windows-1251', $str) , FILE_APPEND);
【解决方案3】:

试试这个(source):

header("Content-type: application/json; charset=utf-8")

$convert = file_put_contents('export.json', json_encode($_REQUEST));
$convert = iconv('CP1251', 'UTF-8', $convert);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 2014-06-07
    • 2013-08-13
    • 1970-01-01
    • 2012-12-23
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多