Using PHP Built‑in JSON Functions to Encode, Decode, and Retrieve Data from APIs
This article explains PHP's native JSON functions—json_encode and json_decode—showing how to convert PHP variables to JSON strings and back, and demonstrates a practical cURL example for fetching and processing JSON data from a remote API.
PHP provides a set of built‑in functions for handling JSON (JavaScript Object Notation) data, allowing developers to easily encode PHP variables into JSON strings and decode JSON strings back into PHP arrays or objects.
Encoding JSON Data
json_encode(): Convert a PHP variable to a JSON string.
$php_array = ['name' => 'John Doe', 'age' => 30];
$json_string = json_encode($php_array);
echo $json_string; // Output: {"name":"John Doe","age":30}Decoding JSON Data
json_decode(): Convert a JSON string to a PHP variable.
$json_string = '{"name":"John Doe","age":30}';
$php_array = json_decode($json_string);
print_r($php_array); // Output: Array ( [name] => John Doe [age] => 30 )Practical Example: Fetching Data from an API
Consider a scenario where cURL is used to retrieve JSON data from an external API and then decode it for further processing.
// Use cURL to fetch JSON data from an API
$url = 'https://example.com/api/v1/users';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Decode the JSON response into a PHP array
$data = json_decode($response);
// Iterate over the data and print each user's name
foreach ($data->users as $user) {
echo $user->name . "\n";
}By leveraging PHP's native JSON functions, developers can effortlessly handle data from APIs or other sources, converting it into PHP variables or strings, which simplifies the development of JSON‑driven applications.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.