JSON PHP – Guide and examples

This article will show 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.

Use the PHP function json_encode() to convert objects in PHP into JSON or use JSON Formatter Online.

PHP file

<?php
$myObj->name = “John”;
$myObj->age = 30;
$myObj->city = “New York”;

$myJSON = json_encode($myObj);

echo $myJSON;
?>

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:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById(“demo”).innerHTML = myObj.name;
}
};
xmlhttp.open(“GET”, “demo_file.php”, true);
xmlhttp.send();

PHP Array

Use the PHP function json_encode() to convert PHP into JSON

PHP file

<?php
$myArr = array(“John”, “Mary”, “Peter”, “Sally”);

$myJSON = json_encode($myArr);

echo $myJSON;
?>

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.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById(“demo”).innerHTML = myObj[2];
}
};
xmlhttp.open(“GET”, “demo_file_array.php”, true);
xmlhttp.send();

PHP Database

Make a request to the server where you ask for the first 10 records in the “customers” table:

Example:

Use JSON.stringify() to convert the JavaScript object into JSON:

obj = { “table”:”customers”, “limit”:10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML = this.responseText;
}
};
xmlhttp.open(“GET”, “json_demo_db.php?x=” + dbParam, true);
xmlhttp.send();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s