Home > Backend Development > PHP Tutorial > How to Parse JSON Responses from cURL using PHP\'s `json_decode` Function?

How to Parse JSON Responses from cURL using PHP\'s `json_decode` Function?

Susan Sarandon
Release: 2024-11-24 19:47:12
Original
511 people have browsed it

How to Parse JSON Responses from cURL using PHP's `json_decode` Function?

Parsing JSON and Extracting Results

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);
Copy after login

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)/"
}
Copy after login

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);
Copy after login

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'];
Copy after login

Now you have easy access to the parsed JSON results and can continue with further processing.

References:

  • [json_decode - PHP Manual](https://www.php.net/manual/en/function.json-decode.php)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template