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


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

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:
1GET /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:
1array (
2    "id" => 18,
3    "first_name" => "Dwayne",
4    "last_name" => "Hicks",
5    "email" => "dwaynehicks@usssulaco.com"
6);
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.
1$output = json_encode($row);
Note: this assumes that your database row is contained within the variable, $row;
Which results in a JSON formatted string:
1{"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. ReturningJSONp 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:
1GET /api/users/18?jsonp=callback
When generating your JSON you just need to wrap the string in the callback response:
1$output $_GET['jsonp'] . '(' . json_encode($row) . ')';
Which would result the following JSON string:
1callback({"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:
1$callback $_GET['jsonp'];
2$output = json_encode($row);
3
4if (isset($callback)) {
5    echo $callback '(' $output ')';
6else {
7    echo $output;
8}
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:
1POST /api/users/
2    {"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:
1$request file_get_contents('php://input');
2
3$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:
1object(stdClass)#1 (3) {
2    ["first_name"] => string(4) "William"
3    ["last_name"] => string(5) "Hudson"
4    ["email"] => string(22) "williamhudson@usssulaco.com"
5}
You can access each attribute as you would any other object property:
1$firstName $input->first_name;
Or iterate through the object:
1foreach ($input as $key=>$value) {
2    echo $key ' = ' $value;
3}
If you prefer to work with arrays, you can create an associative array of the JSONkey=>value pairs by passing a second parameter, true, to the json_decode function. Like so:
1$request file_get_contents('php://input');
2
3$input = json_decode($request, true);
Which would result in the following array:
1array(3) {
2    ["first_name"] => string(4) "William"
3    ["last_name"] => string(5) "Hudson"
4    ["email"] => string(22) "williamhudson@usssulaco.com"
5}
You can access each attribute as you would any other array value:
1$firstName $input['first_name'];
And there we go. Creating JSON data strings for an app to request, or converting JSONstrings 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 .

CD: here

Comments

Popular posts from this blog

รู้จักกับ Breakpoints ใน Responsive Web Design

IS-IS & OSPF

RIP Routing Information Protocol