PHP:json_decode无效

yos*_*shi 20 php json

这并不能正常工作:

$jsonDecode = json_decode($jsonData, TRUE);
Run Code Online (Sandbox Code Playgroud)

但是,如果我复制字符串$jsonData并将其手动放入解码函数中,它确实有效.

有效:

$jsonDecode = json_decode('{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}', TRUE);
Run Code Online (Sandbox Code Playgroud)

我输出$jsonData复制它并在解码函数中输入如上所述.然后它奏效了.但是,如果我$jsonData直接放入解码功能,它不会.

var_dump($jsonData) 说明:

string(144) "{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}"
Run Code Online (Sandbox Code Playgroud)

$jsonData来自一个加密$_GET变量.要加密它我用这个:

$key = "SOME KEY";

$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB, $iv);

$iv = rawurlencode(base64_encode($iv));
$enc = rawurlencode(base64_encode($enc));

//To Decrypt
$iv = base64_decode(rawurldecode($_GET['i']));
$enc = base64_decode(rawurldecode($_GET['e']));

$data = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB, $iv);
Run Code Online (Sandbox Code Playgroud)

小智 50

有时候会出现html实体的问题,例如"它会像这样表示",所以你必须要将html entites解析为真实文本,你可以使用 php的html_entity_decode()方法.

$jsonData = stripslashes(html_entity_decode($jsonData));

$k=json_decode($jsonData,true);

print_r($k);
Run Code Online (Sandbox Code Playgroud)

  • 完善!在解决我的问题之前浪费了一个小时:) (2认同)

lau*_*ent 10

您很可能需要从解密数据中剥离填充.您的字符串中有124个可见字符,但var_dump报告144.这意味着需要删除20个填充字符(字符串末尾的一系列"\ 0"字节).

可能是一个块末尾的4"\ 0"字节+一个空的16字节块(标记数据的结尾).

你目前如何解密/加密你的字符串?

编辑:

你需要添加它来修剪字符串末尾的零字节:

$jsonData = rtrim($jsonData, "\0");
Run Code Online (Sandbox Code Playgroud)


小智 6

您必须使用 preg_replace 来避免 json_decode 的空结果

这是示例代码

$json_string = stripslashes(html_entity_decode($json_string));
Run Code Online (Sandbox Code Playgroud)
$bookingdata =  json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true ); 
Run Code Online (Sandbox Code Playgroud)


dar*_*7yl 5

从其他评论来看,你可以使用,

$ jsonDecode = json_decode(trim($ jsonData),TRUE);


Akh*_*mar 5

在继续 php 7.1 时,我遇到了 json_decode 错误号 4(json 语法错误)。此页面上的上述解决方案均不适合我。

在做了更多搜索之后,我在/sf/answers/1079672961/找到了解决方案,它对我有用。

//Remove UTF8 Bom

function remove_utf8_bom($text)
{
    $bom = pack('H*','EFBBBF');
    $text = preg_replace("/^$bom/", '', $text);
    return $text;
}
Run Code Online (Sandbox Code Playgroud)