如何从CURL解析JSON响应
我正在使用CURL发送请求。响应数据类型为json
。如何解析此数据并将其插入数据库?
<?php$url = 'http://sms2.cdyne.com/sms.svc/SimpleSMSsendWithPostback? PhoneNumber=18887477474&Message=test&LicenseKey=LICENSEKEY';
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$result = curl_exec($cURL);
curl_close($cURL);
print_r($result);
?>
JSON输出:
{ "Cancelled": false,
"MessageID": "402f481b-c420-481f-b129-7b2d8ce7cf0a",
"Queued": false,
"SMSError": 2,
"SMSIncomingMessages": null,
"Sent": false,
"SentDateTime": "/Date(-62135578800000-0500)/"
}
回答:
如果您的$result
变量是字符串json之类的,则必须使用json_decode
function将其解析为 或 :
$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';$json = json_decode($result, true);
print_r($json);
回答:
Array(
[Cancelled] =>
[MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
[Queued] =>
[SMSError] => 2
[SMSIncomingMessages] =>
[Sent] =>
[SentDateTime] => /Date(-62135578800000-0500)/
)
现在,您可以将$json
变量作为数组使用:
echo $json['MessageID'];echo $json['SMSError'];
// other stuff
参考文献:
- json_decode -PHP手册
以上是 如何从CURL解析JSON响应 的全部内容, 来源链接: utcz.com/qa/423862.html