PHP JSON

JSON(JavaScript Object Notation) is text-based data format that use for interchange data between client and server.

JSON is a lightweight and human readable data-interchange format

PHP has some built-in functions for JSON. We are learn two JSON function in this article:

  • json_encode()
  • json_decode()

json_encode() is use for convert PHP Objects into JSON.

    <?php    
        $obj->name = "User 1";
        $obj->email = "user1@gmail.com";

        $json = json_encode($obj);

        echo $json;
    ?>

json_encode() is also use for convert PHP Array into JSON

    <?php    
        $users = array("User 1", "User 2", "User 3");

        $json = json_encode($users);

        echo $json;
    ?>

json_decode() is use to convert JSON string into PHP Object or PHP Array

    <?php    
        $json = '{
                    "name" : "User 1", 
                    "email" : "user1@gmail.com"
                }';

        $decoded_json = json_decode($json); //this function will convert json into PHP Object

        $decoded_json = json_decode($json, true); //this function will convert json into PHP Array

        print_r($decoded_json);
    ?>
PHP Tutorial