Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon

Working with JSON in PHP jQuery

Save for later
  • 5 min read
  • 20 Dec 2010

article-image

 

PHP jQuery Cookbook




working-json-php-jquery-img-0

Over 60 simple but highly effective recipes to create interactive web applications using PHP with jQuery

  • Create rich and interactive web applications with PHP and jQuery
  • Debug and execute jQuery code on a live site
  • Design interactive forms and menus
  • Another title in the Packt Cookbook range, which will help you get to grips with PHP as well as jQuery




        Read more about this book      

In this article, by Vijay Joshi, author of PHP jQuery Cookbook, we will cover:

  • Creating JSON in PHP
  • Reading JSON in PHP
  • Catching JSON parsing errors
  • Accessing data from a JSON in jQuery

(For more resources on this subject, see here.)

Introduction

Recently, JSON (JavaScript Object Notation) has become a very popular data interchange format with more and more developers opting for it over XML. Even many web services nowadays provide JSON as the default output format.

JSON is a text format that is programming-language independent and is a native data form of JavaScript. It is lighter and faster than XML because it needs less markup compared to XML.

Because JSON is the native data form of JavaScript, it can be used on the client side in an AJAX application more easily than XML.

A JSON object starts with { and ends with }. According to the JSON specification, the following types are allowed in JSON:

  • Object: An object is a collection of key-value pairs enclosed between { and } and separated by a comma. The key and the value themselves are separated using a colon (:). Think of objects as associative arrays or hash tables. Keys are simple strings and values can be an array, string, number, boolean, or null.
  • Array: Like other languages, an array is an ordered pair of data. For representing an array, values are comma separated and enclosed between [ and ].
  • String: A string must be enclosed in double quotes
  • The last type is a number

A JSON can be as simple as:

{
"name":"Superman", "address": "anywhere"
}

An example using an array is as follows:

{
"name": "Superman", "phoneNumbers": ["8010367150", "9898989898",
"1234567890" ]
}

A more complex example that demonstrates the use of objects, arrays, and values is as follows:

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at £16.99/month. Cancel anytime

 

{
"people":
[
{
"name": "Vijay Joshi",
"age": 28,
"isAdult": true
},
{
"name": "Charles Simms",
"age": 13,
"isAdult": false
}
]
}

An important point to note:

{
'name': 'Superman', 'address': 'anywhere'
}


Above is a valid JavaScript object but not a valid JSON. JSON requires that the name and value must be enclosed in double quotes; single quotes are not allowed.

Another important thing is to remember the proper charset of data.

Remember that JSON expects the data to be UTF-8 whereas PHP adheres to ISO-8859-1 encoding by default.

Also note that JSON is not a JavaScript; it is basically a specification or a subset derived from JavaScript.

Now that we are familiar with JSON, let us proceed towards the recipes where we will learn how we can use JSON along with PHP and jQuery.

Create a new folder and name it as Chapter 4. We will put all the recipes of this article together in this folder. Also put the jquery.js file inside this folder.

To be able to use PHP's built-in JSON functions, you should have PHP version 5.2 or higher installed.

Creating JSON in PHP

This recipe will explain how JSON can be created from PHP arrays and objects

Getting ready

Create a new folder inside the Chapter4 directory and name it as Recipe1.

How to do it...

  1. Create a file and save it by the name index.php in the Recipe1 folder.
  2. Write the PHP code that creates a JSON string from an array.

    <?php
    $travelDetails = array(
    'origin' => 'Delhi',
    'destination' => 'London',
    'passengers' => array
    (
    array('name' => 'Mr. Perry Mason', 'type' => 'Adult',
    'age'=> 28),
    array('name' => 'Miss Irene Adler', 'type' => 'Adult',
    'age'=> 28)
    ),
    'travelDate' => '17-Dec-2010'
    );
    echo json_encode($travelDetails);
    ?>

  3. Run the file in your browser. It will show a JSON string as output on screen. After indenting the result will look like the following:

    {
    "origin":"Delhi",
    "destination":"London",
    "passengers":
    [
    {
    "name":"Mr. Perry Mason",
    "type":"Adult",
    "age":28
    },
    {
    "name":"Miss Irene Adler",
    "type":"Adult",
    "age":28
    }
    ],
    "travelDate":"17-Dec-2010"
    }

How it works...

PHP provides the function json_encode() to create JSON strings from objects and arrays. This function accepts two parameters. First is the value to be encoded and the second parameter includes options that control how certain special characters are encoded. This parameter is optional.

In the previous code we created a somewhat complex associative array that contains travel information of two passengers. Passing this array to json_encode() creates a JSON string.

There's more...

Predefined constants

Any of the following constants can be passed as a second parameter to json_encode().

  • JSON_HEX_TAG: Converts < and > to u003C and u003E
  • JSON_HEX_AMP: Converts &s to u0026
  • JSON_HEX_APOS: Converts ' to u0027
  • JSON_HEX_QUOT: Converts " to u0022
  • JSON_FORCE_OBJECT: Forces the return value in JSON string to be an object instead of an array

These constants require PHP version 5.3 or higher.