post 请求中的(无效)json 字符串中存在奇怪字符(编码问题)

问题描述 投票:0回答:2

我正在尝试使用以下行从发布请求中获取数据:

$data = file_get_contents('php://input');

问题是当我尝试做

json_decode($data)
时,我得到
null
。通过
var_dump()
ing
$data
,我看到了一些像
\xe0  \xe7a
这样的字符。

发送的数据采用utf-8格式。我也使用

utf8_decode($data)
,但没有运气。有人可以解释我缺少什么或如何解决这个问题吗?

php json character-encoding sanitization
2个回答
1
投票

修复 JSON 的一种方法是用有效的

\xNN
序列替换无效的
\u00NN
序列:

$data = '{"test" : "test one \xe0 "}';
$val = json_decode(str_replace('\x', '\u00', $data));
echo $val->test;

输出:

test one à 

0
投票

用字符串函数改变 json 字符串总是令人担忧的事情,因为误报替换通常很容易损坏有效负载。也就是说,这是一个尝试纠正无效 json 字符串的脚本。

代码:(演示

$json = '{"test" : "test one \xe0, \x270B"}';
    
$json = preg_replace_callback(
           '/\\\\x([[:xdigit:]]+)/',
           fn($m) => sprintf('\u%04s', $m[1]),
           $json
     );
     
echo "\n" . var_export(json_validate($json), true);
echo "\n$json\n";
var_export(json_decode($json));

输出:

true
{"test" : "test one \u00e0, \u270B"}
(object) array(
   'test' => 'test one à, ✋',
)

如果存在已知缺陷,请在下面发表评论,我会在有时间时尽力解决该问题。

我的一个相关答案:用ascii字符替换所有十六进制序列

© www.soinside.com 2019 - 2024. All rights reserved.