Backend Development 4 min read

Understanding PHP json_decode(): Functionality, Parameters, and Example

This article explains PHP's json_decode() function, detailing its purpose, required and optional parameters, and provides a complete code example that demonstrates decoding a JSON string into an associative array and iterating over its contents.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP json_decode(): Functionality, Parameters, and Example

In modern web development, data exchange often uses JSON. PHP provides the json_decode() function to convert JSON strings into PHP objects or arrays. This article introduces the function's capabilities, parameters, and a practical code example.

json_decode() Functionality

The json_decode() function converts a JSON‑formatted string into a PHP object or array, enabling easy access and manipulation of data received from external services or client submissions.

json_decode() Parameters

The function accepts two required and two optional parameters:

string $json : The JSON string to decode.

bool $associative : When true, returns an associative array; otherwise, returns an object (default false).

int $depth : Maximum recursion depth (default 512).

int $options : Bitmask of decoding options such as JSON_BIGINT_AS_STRING , JSON_OBJECT_AS_ARRAY , JSON_THROW_ON_ERROR (default 0).

Code Example

The following example shows how to define a JSON string, decode it into an associative array, and output the name, age, and skill list.

<code><?php

// JSON string
$json_data = '{
    "name": "Tom",
    "age": 25,
    "skills": ["PHP", "JavaScript", "HTML", "CSS"]
}';

// Decode to associative array
$array_data = json_decode($json_data, true);

// Output name and age
echo "姓名:" . $array_data['name'] . "<br>";
echo "年龄:" . $array_data['age'] . "<br>";
echo "技能列表:<br>";

// Output skill list
foreach ($array_data['skills'] as $skill) {
    echo "- " . $skill . "<br>";
}
?>
</code>

The script first defines a JSON string, decodes it with json_decode() into an associative array, then uses a foreach loop to display the name, age, and each skill.

Overall, json_decode() is a vital tool for handling JSON data in PHP, allowing developers to efficiently transform JSON into native PHP structures and improve development productivity.

backendJSONjson_decodephp tutorial
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.