w3resource logo


JSON PHP INSTALLATION & DECODE

Installation of JSON in PHP and PHP json_decode function

Secondary Nav

Description

In this page, you will learn about installing JSON in PHP and about PHP json_decode() function with real world examples.

Installation

PHP 5.2.0 supports JSON out of the box. So, when you install PHP, JSON support is automatically installed and you don't need any installation and configuration in addition.

If your PHP version is less that 5.2.0, you can run the following command on RHEL5/CentOS5 Linux.

sudo yum install php-pecl-json

JSON Functions

JSON supports three PHP functions : json_decode, json_encode and json_last_error. We will discuss all of these functions with examples in the following section of this page.

json_decode() Function

Description

json_decode() function decodes a JSON string. Suppose you have obtained some data in JSON format and you want to convert it into PHP variable for the purpose of presenting that data to a user or use it for further programming, you have to use this function.

PHP Version

PHP 5 >= 5.2.0, PECL json >= 1.2.0

Syntax

json_decode(json_string, assoc, depth, options)

Parameters

Parameters Type Description
json_string String A JSON encoded string. It must be a UTF-8 encoded data.
assoc Boolean If it is true, returned object will be converted into an associative array upon using json_decode function.
depth Integer Specifies recursion depth. This is user specified.
Options Integer Bitmask of JSON decode. As of this writing, only JSON_BIGINT_AS_STRING is supported.

Return Values

json_decode() function returns an supported PHP type. If the available JSON string can not be decoded or if the encoded data is deeper than the recursion limit, it returns NULL. Values true and false are returned as TRUE, FALSE.

Example - fetching last ten tweets from a twitter user's timeline

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PHP JSON installation and json_decode() function | JSON tutorial | w3resource</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
function GetJsonFeed($url)
{
$feed = file_get_contents($url);
return json_decode($feed);
}
$tweets = GetJsonFeed("http://twitter.com/status/user_timeline/w3resource.json?count=10");
// w3resource is the twitter username in question
?>
<h1>Last ten tweets in w3resource's timeline</h1>
<p>
<?php
//Loop through the feed list and display the text part. text is an element in the json feed returned by the twitter API
foreach ($tweets as $tweet)
{
?>
<p>
<?php
echo $tweet -> text;
?>
</p>
<?php
}
?>
</body>
</html>

Note : As far as you are connected to the internet, you can run the above code from localhost also. Replace w3resource with the user name of your choice.

Output of the above Example

.

.

last-ten-tweets-fetched-PHP-JSON w3resource