Memory App
Programming
 




JSON (JavaScript Object Notation) is the actual form that a JavaScript engine will map the object to in memory. PHP have native support for JSON.

json_decode


<?php
    /**
    * json_decode ($json, $assoc = false, $depth)
    * 
    * Return the json representation of a value
    * 
    * This function only works with UTF-8 encoded data.
    * 
    * Retursn NULL - if the json cannot be decoded
    * Retursn NULL - if the encoded data is deeper than the recursion limit.
    *
    */
    
    $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
    var_dump(json_decode($json));
        // object(stdClass) { "a"=> 1, "b"=>2, ... }
    var_dump(json_decode($json, true));
        // array(5) { "a"=> 1, "b"=>2, ... }

    $json = '';
    var_dump(json_decode($json));
        // NULL
(1/3)

json_encode

    
<?php
    /**
    * string json_encode ( mixed $value )
    *
    * Return the json representation of a value
    * 
    * This function only works with UTF-8 encoded data
    * 
    * Returns a JSON encoded string on success or FALSE on failure
    *
    */
    
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    echo json_encode($arr);
        // Outputs: {"a":1,"b":2,"c":3,"d":4,"e":5}
(2/3)

json_last_error


<?php
    /**
    * int json_last_error ( void )
    * 
    * Returns an integer, the value can be one of the JSON error codes constants
    *
    */
    
    // A valid json string
    $json = '{"a": "b"}';
    json_decode($json);
    echo json_last_error();
        // Outputs: 0 (no error)

    // An invalid json string
    $json = "{'a': 'b'}";
    json_decode($json);
    echo json_last_error();
        // Outputs: 4 (JSON_ERROR_SYNTAX)


Questions



Top Reference > Programming