Horje
How to JSON Decode in PHP?

JSON Decode is the process of converting a JSON string into a PHP variable, typically an object or an associative array. Then we will print that decode JSON text.

Below are the approaches to JSON decoding in PHP:

Using json_decode() method

In this approach, we use json_decode() in PHP to parse a JSON string into an object. We then check if the decoding was successful and display the decoded values such as Name, Age, and City otherwise, it shows a failure message.

Example: The below example uses json_decode() to JSON Decode in PHP.

PHP
<?php
$json_data = '{"name": "GFG", "age": 30, "city": "Noida"}';
$res = json_decode($json_data);
if ($res !== null) {
    echo "Name: " . $res->name . "<br>";
    echo "Age: " . $res->age . "<br>";
    echo "City: " . $res->city . "<br>";
} else {
    echo "Failed to decode JSON data.";
}
?>

Output:

Name: GFG
Age: 30
City: Noida

Using Explode and Foreach Loop

In this approach, This PHP code decodes JSON data using the explode function and a foreach loop. It replaces unnecessary characters, splits the data into key-value pairs, and stores them in an associative array. Finally, it prints specific values like name, age, and city.

Example: The below example uses Explode and Foreach Loop to JSON Decode in PHP.

PHP
<?php
$json_data = '{"name": "GFG", "age": 30, "city": "Noida"}';
$json_data = str_replace(["{", "}", '"'], "", $json_data);
$key_Val = explode(",", $json_data);
$res = [];
foreach ($key_Val as $pair) {
    list($key, $value) = explode(":", $pair, 2);
    $key = trim($key);
    $value = trim($value);
    $res[$key] = $value;
}
echo "Name: " . $res["name"] . "<br>";
echo "Age: " . $res["age"] . "<br>";
echo "City: " . $res["city"] . "<br>";
?>

Output:

Name: GFG
Age: 30
City: Noida



Reffered: https://www.geeksforgeeks.org


PHP

Related
How to Remove First Element from an Array in PHP? How to Remove First Element from an Array in PHP?
How to Check if a Value Exists in an Associative Array in PHP? How to Check if a Value Exists in an Associative Array in PHP?
How to Check if a Key Exists in an Associative Array in PHP? How to Check if a Key Exists in an Associative Array in PHP?
How to Get All Keys of an Associative Array in PHP? How to Get All Keys of an Associative Array in PHP?
How to Check Whether a Variable is Empty in PHP? How to Check Whether a Variable is Empty in PHP?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13