JavaScript Tutorial
JS - Introduction JS - Basic JS - Placement JS - Output JS - Statements JS - Syntax JS - Variables JS - Comments JS - Data Types JS - Operators JS - Operator Precedence JS - Condition JS - Switch JS - Functions JS - Objects JS - Loops For JS - Loops While JS - Break JS - Strings JS - String Methods JS - Numbers JS - Number Methods JS - Arrays JS - Array Methods JS - Array Iteration JS - Events JS - Event Listener JS - Event Propagation JS - Date JS - Math JS - Random JS - Boolean JS - Type Conversion JS - RegExp JS - Exception JS - Scope JS - Debugging JS - Hoisting JS - Strict Mode JS - this Keyword JS - Mistakes JS - Best Practices JS - Performance JS - Form Validation JS - ES6 Features
JS Objects
Object Definitions Object Properties Object Methods Object Constructors Object Prototypes
JS Functions
Function Definitions Function Parameters Function Call Function Apply Function Closures
JS HTML DOM
DOM Introduction DOM Methods DOM Selectors DOM HTML DOM CSS DOM Attributes DOM Navigation
JS Browser BOM
JS - Window JS - Screen JS - Location JS - History JS - Navigator JS - Popup Alert JS - Timing JS - Cookies
JS AJAX
AJAX - Introduction AJAX - XMLHttp AJAX - Request AJAX - Response AJAX - PHP
JS JSON
JSON - Introduction JSON - Syntax JSON - Data Types JSON - Parse JSON - Stringify JSON - Objects JSON - Arrays JSON - PHP JSON - JSONP
JS References
JavaScript Reference JavaScript Methods HTML DOM Reference

JSON PHP

A common use of JSON is to send/read data to/from a web server, and display the data in a web page.

This chapter covers how to exchange JSON data between the client and a PHP server.


PHP JSON Functions

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default.

PHP has following built-in functions to handle JSON:

Function Description
json_encode() Returns the JSON representation of a value
json_decode() Decodes a JSON string
json_last_error() Returns the last error occurred

The json_encode() Function

Objects in PHP can be converted into JSON by using the PHP function json_encode().

The given file is saved by json_demo1.php:

The following example requests the PHP file from the example above (json_demo1.php) and convert the response into a JavaScript object using JSON.parse():

Run code

Arrays in PHP will also be converted into JSON by using the PHP function json_encode().

The given file is saved by json_demo2.php:

The following example requests the PHP file from the example above (json_demo2.php) and convert the response into a JavaScript array using JSON.parse():

Run code

The json_decode() Function

JSON string can be converted into PHP objects using function json_decode().

The given file is saved by json_demo.php:

The following example converts a JavaScript object into a JSON string, and send it to the server (demo_json.php):

Run code

JSON string can be converted into PHP arrays using function json_decode().