Sam Croft

Full-stack developer

Tutorial: Using PHP's JSON encode and decode functions to handle data sent to and from your app


Filed in: api, apps, JSON, PhoneGap, php, Uncategorized

JSON makes dealing with data in your app exceptionally easy and manageable. The best part about JSON is you can look at it and understand it. It’s not like the confusing spaghetti DOM that you get with XML, it’s a lean minimal representation of your data. If you’re dealing with chunks of data in your app, you want to be using JSON.

So while your app will happily eat up all the JSON you can throw at it, you still need to make it in the first place – and/or have a server side app that is capable of reading it. If, like me, you use PHP to handle things on a server then things are pretty straightforward. You can use PHP’s json_encode and json_decode functions. Encode will take your arrays, or objects, and create a JSON string of your data. While decode will take a JSON string, sent from your app, and turn it into an array or object.

Using PHP’s JSON encode function to create JSON from an array

Let’s consider a situation where your app is requesting some details. It might make a request to your api to get information about a user.

From an app you might make this request:

GET /api/users/18

Over on the server let’s assume there is some code that retrieves user 18’s details from a database, returning the row as an array. If you’re building an associative array from your database query the row could look like this:

array (
	"id" => 18,
	"first_name" => "Dwayne",
	"last_name" => "Hicks",
	"email" => ""

To convert this array to a JSON string that an app could use you just need to run it through PHP’s json_encode function.

$output = json_encode($row);

Note: this assumes that your database row is contained within the variable, $row;

Which results in a JSON formatted string:


You can then take this JSON string in your app and extract the necessary data.

Generating JSON for a web app? Don’t forget JSONp

If you’re going to be using JSON in a web app you may need to consider JSONp, which allows you to make a cross-domain request if you JSON is being created on another domain. JSONp is JSON with a custom callback function wrapped around it. Returning JSONp is very simple, you just need to pass your JSON resource the callback parameter and wrap the JSON in its value.

Using the same example as above, from your app you would make the request but with a callback parameter:

GET /api/users/18?jsonp=callback

When generating your JSON you just need to wrap the string in the callback response:

$output = $_GET['jsonp'] . '(' . json_encode($row) . ')';

Which would result the following JSON string:


For best practice, check whether or not there is a JSONp callback parameter and serve the necessary format of JSON:

$callback = $_GET['jsonp'];
$output = json_encode($row);

if (isset($callback)) {
	echo $callback . '(' . $output . ')';
} else {
	echo $output;

That covers creating JSON for you app. Now let’s look at dealing with JSON, submitted from your app to your server for processing.

Using PHP’s JSON decode function to create an object or array from a JSON string

Submitting a JSON formatted string from your app to your web server is a great way to transmit data. PHP’s json_decode function takes a JSON string and converts it to an object (by default) or an array, making each attribute easy to handle.

Going back to our fictional app again, let’s consider how a new user might be created. You might make the following request to submit some new user data to your server:

POST /api/users/

Creating an object from the submitted JSON

Using json_decode is as simple as json_encode:

$request = file_get_contents('php://input');

$input = json_decode($request);

Note: I am using php://input, a read-only stream, instead of PHP_POST variables. This is because the POST’ed data was not submitted as a key=>value pair (unlike normal form submissions). This method takes all of the raw submitted data in one chunk making it ideal for use with JSON as we need it all as one string before breaking it down.

By default json_decode creates an object. The result of the above would be as follows:

object(stdClass)#1 (3) {
	["first_name"] => string(4) "William"
	["last_name"] => string(5) "Hudson"
	["email"] => string(22) ""

You can access each attribute as you would any other object property:

$firstName = $input->first_name;

Or iterate through the object:

foreach ($input as $key=>$value) {
	echo $key . ' = ' . $value;

If you prefer to work with arrays, you can create an associative array of the JSON key=>value pairs by passing a second parameter, true, to the json_decode function. Like so:

$request = file_get_contents('php://input');

$input = json_decode($request, true);

Which would result in the following array:

array(3) {
	["first_name"] => string(4) "William"
	["last_name"] => string(5) "Hudson"
	["email"] => string(22) ""

You can access each attribute as you would any other array value:

$firstName = $input['first_name'];

And there we go. Creating JSON data strings for an app to request, or converting JSON strings submitted from an app, couldn’t be simpler.

About the author

I'm Sam Croft a full-stack developer with over 15 years experience in web and app development. For the last six years I have been a partner of Running in the Halls, an app and game design studio based in Huddersfield, UK. During this time I have developed many web and applications. Highlights include a node.js/ app to create the worlds largest crowd-based game on the first series of Channel 4's Gadget Man with Stephen Fry and Librarygame, a Library gamification platform for Universities. Librarygame is being played by over 6,000 students at The Open University, The University of Manchester, The University of Glasgow and The University of Huddersfield.

In my spare time I enjoy long distance running, watching all sports (especially F1) and playing video games. I live in the Holme Valley in West Yorkshire with my wife, Alex.

Sometimes I tweet.