Json - With PHP Decode


Json - With PHP Decode

json_decode():

1.The json_decode() with single PHP variable returns a JSON "object" as PHP object of type stdClass. 

2.When a second argument, a Boolean value is added to the json_decode(),JSON objects return a PHP associative arrays.

Sample Code :

<?php
    $WikiTechy_employees =  
        '{"firstName":"jln","lastName":"jayaka" }';    
    $json_value = json_decode( $WikiTechy_employees );
    echo $json_value->firstName . "<br>";   
    echo $json_value->lastName  ;
?>

Code Path :

  • Type the above code in an editor such as notepad and save it with “.php” file extension in the following path as shown below:

    The element <?php will indicates the browser that it is a PHP code.

    A variable $WikiTechy_employeesis declared.

    The variable $WikiTechy_employeeshas a firstname and lastname attributes as follows: 

    $WikiTechy_employees =   '{"firstName":"jln","lastName":"jayaka" }';    

    The line of code $json_value = json_decode( $WikiTechy_employees ); decodes the value of variable $WikiTechy_employeesinto a JSON object.

    The code echo $json_value->firstName . "<br>";   prints the value of firstName from decoded variable $json_value.

    The code echo $json_value->lastName  ;prints the value of firstName from decoded variable $json_value.

Execution :

  • Go to browser and type http://localhost:85/json_wikiTechy/10.json-with-php.php to execute the above code.

Sample Output :

    The code echo $json_value->firstName . "<br>"; prints the output in browser as “jln” and adds a line break.

    The code echo $json_value->lastName  ;prints the output in browser as “jayaka”.