Sam Croft

A designer/developer on HTML, CSS, JavaScript and PhoneGap

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

  • 2 comments

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

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" => "dwaynehicks@usssulaco.com"
);

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:

{"id":18,"first_name":"Dwayne","last_name":"Hicks","email":"dwaynehicks@usssulaco.com"}

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:

callback({"id":18,"first_name":"Dwayne","last_name":"Hicks","email":"samcroft@usssulaco.com"})

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/
	{"first_name":"William","last_name":"Hudson","email":"williamhudson@usssulaco.com"}

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) "williamhudson@usssulaco.com"
}

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) "williamhudson@usssulaco.com"
}

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 thirtysomething designer/developer and co-founder of Running in the Halls Ltd—a web and app development studio in Huddersfield, UK. I was educated in graphic design and now specialise in front-end web and app development; my main passion being usability and accessibility. I strongly believe web apps (vs native) are the future and love developing for mobile using the wonderful PhoneGap.

I am a massive sports fan - Formula One in particular. I live in the Pennines with my beautiful wife, Alex. Occasionally I own a large scruffy beard.

I tweet about all of my interests - you should follow me. I also have a .