[英]json_decode return null on valid string?
Hi I have this simple string called $response1:
嗨,我有一个名为$response1:
简单字符串$response1:
{"SN":"5054494EA805743F","MAC":"CC:19:A8:xx:xx:xx","customerName":"John doe ","id":"6666","serviceID":"1000","jobid":"12345"}
Essentially I get this string from a curl request but when I do "$ree = json_decode($response1);
print_r($ree);
return null.基本上我从 curl 请求中得到这个字符串,但是当我做"$ree = json_decode($response1);
print_r($ree);
return null.
Here is the snippet这是片段
$response1 = curl_exec($ch2);
$ree = json_decode($response1);
print_r($dee);
print_r($response1);
JSON checkers says the string is okay, and json_last_error()
returns 0 JSON 检查器说字符串没问题,而json_last_error()
返回 0
What is going on here ?这里发生了什么 ?
All the code as requested要求的所有代码
<?php
$ch2 = curl_init();
//initiate http curl connection.
curl_setopt_array($ch2, array(
CURLOPT_URL => "http://x.x.x.x/Testingsomething.php",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"JobId\"\r\n\r\nXXXXXXX\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundaryXXXXXXXX",
),
));
//$response1 = curl_exec($ch2);
//$ree = json_decode($response1, true, JSON_THROW_ON_ERROR);
//print_r($ree);
//echo $ree["ontserial"];
try {
$response1 = curl_exec($ch2);
$ree = json_decode($response1, true, 512, JSON_THROW_ON_ERROR);
print_r($response1);
print_r($ree);
echo $ree;
}
catch (\JsonException $exception) {
echo $exception->getMessage(); // displays "Syntax error"
}
Since PHP 7.3, the json_decode
function will accept a new JSON_THROW_ON_ERROR
option that will let json_decode throw an exception instead of returning null on error.Thats is how you find the issue.自 PHP 7.3 起, json_decode
函数将接受一个新的JSON_THROW_ON_ERROR
选项,该选项将使 json_decode 抛出异常而不是在错误时返回 null。这就是您发现问题的方式。
Please try with below solution:请尝试以下解决方案:
try {
$response1 = curl_exec($ch2);
$ree =json_decode($response1, false, 512, JSON_THROW_ON_ERROR);
}
catch (\JsonException $exception) {
echo $exception->getMessage(); // displays "Syntax error"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.