json_decode返回NULL,UTF-8 BOM

时间:2012-11-27 11:12:07

标签: php json utf-8 byte-order-mark

我想解码JSON数据并使用json_decode函数将其存储到数组中,但它返回NULL值。我认为这是因为UTF-8 BOM。任何方案? 我在xampp上使用Windows7操作系统。 我将我的编码设置为

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

JSON DATA

{"command":"E101","user_id":"someuser","movie_id":"1","link_id":"2"}

JSON错误:控制字符错误,可能编码错误

 $json_errors = array(
     JSON_ERROR_NONE => 'No error has occurred',
     JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
     JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
     JSON_ERROR_SYNTAX => 'Syntax error',
    );
    echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;

如果我解析此JSON,则无错误

 {"command":"E101","user_id":"someuser","movie_id":"movie_id","link_id":"link_id"}

唯一的区别是我将字符串数据存储到movie_id和link_id中。为什么会这样?

JSON Data Bin2Hex()     7b22636f6d6d616e64223a2245313031222c226d6f7669655f6964223a226d6f7669655f6964222c226c696e6b5f6964223a226c696e6b5f6964227d00000000

Im加密JSON数据并通过客户端,我在服务器端解密。

这是我的加密功能

    public function ajax_enc($data){

    $vector = "myvector";
    $filter = new Zend_Filter_Encrypt(array('adapter' => 'mcrypt', 'key' => $this->_AJAXKEY));
    $filter->setVector($vector);
    $encrypted = $filter->filter($data);
    // bin2hex for user use case     
    return bin2hex($encrypted); // rawurlencode(..) works

    }

解密

public function ajax_dec($data)
{
$vector = "myvector";
$filter = new Zend_Filter_Decrypt(array('adapter' => 'mcrypt', 'key' => $this->_AJAXKEY ));
$filter->setVector($vector);
$decoded = pack('H*', $data);
$decrypted = $filter->filter($decoded);
return $decrypted;
}

2 个答案:

答案 0 :(得分:3)

你的解密显然在字符串末尾留下了一堆填充NUL字节。

修复解密机制或修剪它们:trim($json, "\x0")

答案 1 :(得分:1)

要删除,请执行以下操作:

$json_raw_str = ltrim($json_raw_str, chr(239).chr(187).chr(191));

为什么?因为Byte_order_mark 239 187 191的十进制表示形式,并且ltrim从字符串的开头将其删除。

执行此操作后:

$data = json_decode($json_raw_str);
// be fun :)