Using PHP json_decode to Convert JSON Strings to PHP Variables
This article explains how PHP's json_decode function can transform JSON-formatted strings into PHP objects or associative arrays, demonstrates usage with code examples, and shows the resulting output for both object and array conversions.
When handling data in web applications, it is often necessary to convert data from one encoding format to another; a common conversion is turning a JSON‑formatted string into a PHP variable, which can be done easily with PHP's built‑in json_decode function.
The json_decode function accepts a JSON string as its first argument and returns a PHP variable that mirrors the structure of the JSON data, either as an object or, when requested, as an associative array.
Below is a basic example that decodes a JSON string into a PHP object and prints the result.
<?php
$jsonString = '{"name":"John","age":30,"city":"New York"}';
// Convert JSON string to PHP variable
$phpArray = json_decode($jsonString);
// Print the PHP variable
print_r($phpArray);
?>Running this code outputs an object whose properties correspond to the JSON keys and values:
stdClass Object ( [name] => John [age] => 30 [city] => New York )In addition to returning an object, json_decode can produce an associative array by passing true as the second parameter. The following example demonstrates this conversion.
<?php
$jsonString = '[{"name":"John","age":30,"city":"New York"},{"name":"Jane","age":25,"city":"London"}]';
// Convert JSON string to PHP array
$phpArray = json_decode($jsonString, true);
// Print the PHP array
print_r($phpArray);
?>Executing the code yields an array of associative arrays, each representing a person from the JSON data:
Array (
[0] => Array ( [name] => John [age] => 30 [city] => New York )
[1] => Array ( [name] => Jane [age] => 25 [city] => London )
)In summary, PHP's json_decode function provides a straightforward way to convert JSON strings into PHP objects or arrays, making it a valuable tool for processing data in web 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.