- JSON PHP
- The PHP File
- PHP file
- The Client JavaScript
- Example
- PHP Array
- PHP file
- The Client JavaScript
- Example
- PHP Database
- Example
- Example explained:
- PHP file
- PHP File explained:
- Use the Data
- Example
- PHP Method = POST
- Example
- PHP file
- PHP JSON
- PHP JSON extension
- Converting PHP variables to JSON using json_encode() function
- Converting JSON data to PHP variables
- Serializing PHP objects
- Summary
JSON PHP
A common use of JSON is to read data from a web server, and display the data in a web page.
This chapter will teach you how to exchange JSON data between the client and a PHP server.
The PHP File
PHP has some built-in functions to handle JSON.
Objects in PHP can be converted into JSON by using the PHP function json_encode() :
PHP file
The Client JavaScript
Here is a JavaScript on the client, using an AJAX call to request the PHP file from the example above:
Example
Use JSON.parse() to convert the result into a JavaScript object:
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() const myObj = JSON.parse(this.responseText);
document.getElementById(«demo»).innerHTML = myObj.name;
>
xmlhttp.open(«GET», «demo_file.php»);
xmlhttp.send();
PHP Array
Arrays in PHP will also be converted into JSON when using the PHP function json_encode() :
PHP file
The Client JavaScript
Here is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above:
Example
Use JSON.parse() to convert the result into a JavaScript array:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() const myObj = JSON.parse(this.responseText);
document.getElementById(«demo»).innerHTML = myObj[2];
>
xmlhttp.open(«GET», «demo_file_array.php», true);
xmlhttp.send();
PHP Database
PHP is a server side programming language, and can be used to access a database.
Imagine you have a database on your server, and you want to send a request to it from the client where you ask for the 10 first rows in a table called «customers».
On the client, make a JSON object that describes the numbers of rows you want to return.
Before you send the request to the server, convert the JSON object into a string and send it as a parameter to the url of the PHP page:
Example
Use JSON.stringify() to convert the JavaScript object into JSON:
const limit = <"limit":10>;
const dbParam = JSON.stringify(limit);
xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() document.getElementById(«demo»).innerHTML = this.responseText;
>
xmlhttp.open(«GET»,»json_demo_db.php?x=» + dbParam);
xmlhttp.send();"limit":10>
Example explained:
- Define an object containing a «limit» property and value.
- Convert the object into a JSON string.
- Send a request to the PHP file, with the JSON string as a parameter.
- Wait until the request returns with the result (as JSON)
- Display the result received from the PHP file.
Take a look at the PHP file:
PHP file
header(«Content-Type: application/json; charset=UTF-8»);
$obj = json_decode($_GET[«x»], false);
?php
$conn = new mysqli(«myServer», «myUser», «myPassword», «Northwind»);
$stmt = $conn->prepare(«SELECT name FROM customers LIMIT ?»);
$stmt->bind_param(«s», $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
PHP File explained:
- Convert the request into an object, using the PHP function json_decode() .
- Access the database, and fill an array with the requested data.
- Add the array to an object, and return the object as JSON using the json_encode() function.
Use the Data
Example
xmlhttp.onload = function() <
const myObj = JSON.parse(this.responseText);
let text = «»;
for (let x in myObj) <
text += myObj[x].name + «
«;
>
document.getElementById(«demo»).innerHTML = text;
>
PHP Method = POST
When sending data to the server, it is often best to use the HTTP POST method.
To send AJAX requests using the POST method, specify the method, and the correct header.
The data sent to the server must now be an argument to the send() method:
Example
const dbParam = JSON.stringify(<"limit":10>);
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() const myObj = JSON.parse(this.responseText);
let text =»»;
for (let x in myObj) text += myObj[x].name + «
«;
>
document.getElementById(«demo»).innerHTML = text;
>
xmlhttp.open(«POST», «json_demo_db_post.php»);
xmlhttp.setRequestHeader(«Content-type», «application/x-www-form-urlencoded»);
xmlhttp.send(«x=» + dbParam);"limit":10>
The only difference in the PHP file is the method for getting the transferred data.
PHP file
Use $_POST instead of $_GET:
header(«Content-Type: application/json; charset=UTF-8»);
$obj = json_decode($_POST[«x»], false);
$conn = new mysqli(«myServer», «myUser», «myPassword», «Northwind»);
$stmt = $conn->prepare(«SELECT name FROM customers LIMIT ?»);
$stmt->bind_param(«s», $obj->limit);
$stmt->execute();
$result = $stmt->get_result();
$outp = $result->fetch_all(MYSQLI_ASSOC);
?php
PHP JSON
Summary: in this tutorial, you will learn how to convert data in PHP to JSON data and vice versa using the PHP JSON extension.
JSON stands for JavaScript Object Notation. JSON is designed as a lightweight data-interchange format.
JSON is built on two structures:
- A collection of name/value pairs called JSON objects. JSON objects are equivalent to associative arrays in PHP.
- An ordered list of values called arrays. They’re equivalent to indexed arrays in PHP.
The JSON format is human-readable and easy for computers to parse. Even though JSON syntax derives from JavaScript, it’s designed to be language-independent.
PHP JSON extension
PHP natively supports JSON via the JSON extension. The JSON extension provides you with some handy functions that convert data from PHP to JSON format and vice versa.
Since the JSON extension comes with PHP installation by default, you don’t need to do any extra configuration to make it works.
Converting PHP variables to JSON using json_encode() function
To get a JSON representation of a variable, you use the json_encode() function:
json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|false
Code language: PHP (php)
The following example uses the json_encode() function to convert an indexed array in PHP to JSON format:
$names = ['Alice', 'Bob', 'John']; $json_data = json_encode($names); // return JSON to the browsers header('Content-type:application/json'); echo $json_data;
Code language: PHP (php)
- First, define an array of strings that consists of three elements.
- Second, convert the array to JSON using the json_encode() function.
- Third, return the JSON data to the browsers by setting the content type of the document to appplication/json using the header() function.
[ "Alice", "Bob", "John" ]
Code language: JSON / JSON with Comments (json)
The following example uses the json_encode() function to convert an associative array in PHP to an object in JSON:
$person = [ 'name' => 'Alice', 'age' => 20 ]; header('Content-type:application/json'); echo json_encode($person);
Code language: PHP (php)
< name: "Alice", age: 20 >
Code language: PHP (php)
In practice, you would select data from a database and use the json_encode() function to convert it to the JSON data.
Converting JSON data to PHP variables
To convert JSON data to a variable in PHP, you use the json_decode() function:
json_decode ( string $json , bool|null $associative = null , int $depth = 512 , int $flags = 0 ) : mixed
Code language: PHP (php)
The following example shows how to use json_decode() function to convert JSON data to a variable in PHP:
$json_data = ''; $person = json_decode($json_data); var_dump($person);
Code language: PHP (php)
object(stdClass)#1 (2) ["name"] => string(5) "Alice" ["age"] => int(20) >
Code language: PHP (php)
In this example, the json_decode() function converts an object in JSON to an object in PHP. The object is an instance of the stdClass class. To convert JSON data to an object of a specific class, you need to manually map the JSON key/value pairs to object properties. Or you can use a third-party package.
Serializing PHP objects
To serialize an object to JSON data, you need to implement the JsonSerializable interface. The JsonSerializable interface has the jsonSerialize() method that specifies the JSON representation of the object.
For example, the following shows how to implement the JsonSerializable interface and use the json_encode() function to serialize the object:
class Person implements JsonSerializable < private $name; private $age; public function __construct(string $name, int $age) < $this->name = $name; $this->age = $age; > public function jsonSerialize() < return [ 'name' => $this->name, 'age' => $this->age ]; > > // serialize object to json $alice = new Person('Alice', 20); echo json_encode($alice);
Code language: PHP (php)
"name"
:"Alice","age":20>Code language: PHP (php)
- First, define a Person class that implements the JsonSerializable interface.
- Second, return an array that consists of name and age properties from the jsonSerialize() method. The json_encode() function will use the return value of this method to create JSON data.
- Third, create a new Person object and serialize it to JSON data using the json_encode() function.
Summary
- JSON is a lightweight data-interchange format.
- Use the json_encode() function to convert PHP variables to JSON.
- Use the json_decode() function to convert JSON data to PHP variables.
- Implement the JsonSerializable interface to specify the JSON representation of an object.