Backend Development 4 min read

Using PHP json_decode to Convert JSON Strings to PHP Variables

This article explains how PHP's built-in json_decode function converts JSON-formatted strings into PHP variables, demonstrating both object and associative array outputs with code examples, and shows how to adjust parameters to obtain the desired data structure.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP json_decode to Convert JSON Strings to PHP Variables

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 PHP provides via the built‑in json_decode function.

The json_decode function accepts a JSON string as its first argument and returns a corresponding PHP variable.

Below is a basic example that decodes a JSON string into a PHP object:

<?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 script outputs a stdClass object with properties name , age , and city , demonstrating that json_decode successfully transformed the JSON string into a PHP object.

By passing true as the second argument, json_decode returns an associative array instead of an object. The following example shows this usage:

<?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 script produces a nested PHP array where each element corresponds to an object from the original JSON, confirming that json_decode can also produce arrays.

In summary, PHP’s json_decode function provides a straightforward way to convert JSON strings into PHP objects or associative arrays, which is essential for processing data in web applications.

backendJSONPHPData Conversionjson_decode
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.