PHP json_encode and json_decode method

PHP json_encode and json_decode method

    PHP provides method to convert PHP object to json and json PHP object. Two method are used often json_encode() and json_decode()

    json_encode() method

    This method takes a PHP object like an array and convert to json object. Use it when you to show data as json or store data in database field as json.

    Use cases

    1. present data as json
    2. store data in database as json
    3. store two dimentional data in database

    You may also wanna use array_values() with json_encode() function.

    Look at the below the function print log. 

    In the above case if you just want name, thumbain and url field you should array_values() inside json_encode(). Now the code with json_encode() looks like below

    json_decode() method

    This method takes a json object and convert to PHP object.

    $jsonString = '{"name":"John", "age":30, "city":"New York"}';
    $data = json_decode($jsonString);
            
    echo $data->name;  // Output: John
    echo $data->age;   // Output: 30
    echo $data->city;  // Output: New York

    Another example of this would be below

    Here we decode $value, in this we also set a second argument as true. With this json_decode() would return associative array.

    Otherwise you just returns an array.

    If you have nested json data, then you need to pass true as second argument. If your json data is complex, you may need to go through foreach loop.

    Summary

    Use json_encode() if you to store data as json in the database, use json_decode() after retreiving the data from the database.

    Courses


    Recommended posts


    Recent posts