When handling responses from web services that transmit data in JSON format, parsing the response and extracting its results is crucial for further processing. Here's how to accomplish this using PHP's cURL and json_decode functions:
Given a sample cURL request:
$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);
The response from this request is a JSON string, as seen below:
{ "Cancelled": false, "MessageID": "402f481b-c420-481f-b129-7b2d8ce7cf0a", "Queued": false, "SMSError": 2, "SMSIncomingMessages": null, "Sent": false, "SentDateTime": "/Date(-62135578800000-0500)/" }
To parse this JSON string and convert it into an array or object that is easier to work with, use PHP's json_decode function:
$json = json_decode($result, true);
By setting the second parameter of json_decode to true, the output will be an associative array. This makes it easier to access the JSON data using array keys, as shown below:
echo $json['MessageID']; echo $json['SMSError'];
Now you have easy access to the parsed JSON results and can continue with further processing.
References:
The above is the detailed content of How to Parse JSON Responses from cURL using PHP\'s `json_decode` Function?. For more information, please follow other related articles on the PHP Chinese website!