HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. PHP has built-in functions to handle JSON data efficiently.


What is JSON?

JSON is a text-based format used to represent structured data. It is the industry standard for sending data from a server to a web page (via AJAX) or between different web services (APIs).

Common Use Case: When you fetch data from an API (like weather info or social media feeds), the data is almost always delivered in JSON format.

1. PHP json_encode()

The json_encode() function is used to convert a PHP array or object into a JSON string.

<?php
    $age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);

    // Convert PHP associative array to JSON string
    echo json_encode($age);
    // Output: {"Peter":35,"Ben":37,"Joe":43}
?>

2. PHP json_decode()

The json_decode() function is used to convert a JSON string back into a PHP object or an associative array.

Decoding into an Object

By default, json_decode() returns an object.

<?php
    $jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

    $obj = json_decode($jsonobj);

    echo $obj->Peter; // Accessing as object property
?>

Decoding into an Associative Array

If you pass true as the second parameter, it returns an associative array instead of an object.

<?php
    $jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

    $arr = json_decode($jsonobj, true);

    echo $arr["Peter"]; // Accessing as array element
?>

Looping Through Decoded Data

Once you've decoded the JSON into a PHP array, you can loop through it using foreach.

<?php
    $jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
    $arr = json_decode($jsonobj, true);

    foreach($arr as $key => $value) {
        echo $key . " is " . $value . " years old.<br>";
    }
?>
Note: JSON keys and strings must be enclosed in double quotes ("). Single quotes are not valid in JSON.

Summary

  • JSON is a universal data exchange format.
  • json_encode(): PHP Array/Object -> JSON String.
  • json_decode(): JSON String -> PHP Object/Array.
  • The second parameter of json_decode() determines if you get an object (false) or an associative array (true).
Pro Tip: When building modern web apps with frameworks like React or Vue, your PHP back-end will mostly communicate by sending json_encode() results.

What's Next?

JSON is the foundation for asynchronous communication. Next, we'll see how to use it with **PHP AJAX** to create faster, smoother user experiences.