我正在使用CURL发送请求。响应数据类型为json。如何解析这些数据并将其插入数据库?
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_decodefunction将其解析为 对象 或 数组 :
$result
json_decode
$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变量作为数组使用:
$json
echo $json['MessageID']; echo $json['SMSError']; // other stuff
参考文献: