2016-02-11 44 views
1

我想删除特殊字符(并发现这个在论坛):json_decode() - 语法错误

$response = trim(preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $response)); 

同样对于这个

for ($i = 0; $i <= 31; ++$i) { 
    $response = str_replace(chr($i), "", $response); 
} 

$response = str_replace(chr(127), "", $response); 

if (0 === strpos(bin2hex($response), 'efbbbf')) { 
    $response = substr($response, 3); 
} 

而这个编码

$response = mb_convert_encoding($response, "UTF-8"); 
echo "\nJSON Response:#$response#\n"; 

此时$response回声:

{"data":{"taxa":[{"placa":"EDY8986","taxas_detran":"141.36","seguro_dpvat":"211.30","ipva":"1945.20","multas":"5048.10","total_debitos":"null"}]},"code":200,"pagination":{"rows":1,"page":1,"pages":0,"hasNext":false,"totalRows":1}} 

最终

$data = json_decode('"' . $response . '"',true, 512); 
echo "\n\nData>\n"; 
print_r($data); 
echo "\nError> "; echo json_last_error_msg(); 

json_last_error_msg()打印:

Syntax Error

我已经在JSONLint和JSON格式程序验证它,它是有效的。

+2

'$数据= json_decode($响应,真实,512);' –

+0

我不能相信它。也许我疯了。谢谢你,它的工作! –

回答

2

你只是需要littile位的变化,它很好地工作: -

$data = json_decode($response,true, 512);// remove quotes 
1

你杀了你的JSON与额外的引号:

$data = json_decode('"' . $response . '"',true, 512); 
         ^-----------------^ 

假设你的$回应

{"foo":"bar"} 

然后你会产生/传递

"{"foo":"bar"}" 

这是一个彻底的JSON语法错误:

"{"foo":"bar"}" 
^--start string 
    ^-end string 
    ^^^---????