In this tutorial, we are going to learn how to use the JSON with PHP. JSON is a simple way to store and exchange information. JSON is a lightweight than XML, faster and easier to parse with any programming language. The output of JSON encoded data is very easy to read by both humans and machines. There are two JSON validation schema libraries made for PHP : php-json-schema and json-schema. As of PHP 5.2 the support for JSON parsing is built-in with extension. This bundled extension is shipped with any php server like XAMPP and Bitnami to help you work with JSON.
You can learn more about JSON in more depth and with examples in JavaScript: The Definitive Guide.
Where and Why to use JSON in PHP?
Some of the web services like twitter offer the output only via JSON. You can parse JSON data with the help of PHP or any other programming language and use the data as per your needs. Also when you write AJAX related to program then writing code in JSON is quicker compared to XML.
There are three functions that we are going to work on – json_encode, json_decode and json_last_error.
Let’s start with our first function json_encode().
This code will produce result like this:
{"a":"apple","b":"ball","c":"cat","d":"dog","e":"elephant"}
Code explanation: The json_encode() function is used to encode the JSON in PHP language.
Now let’s see how to use json_decode function. In order to decode the JSON, let’s use the test JSON data from our previous example.
This code should produce output like this:
object(stdClass)#1 (5) {
["a"]=>
string(5) "apple"
["b"]=>
string(4) "ball"
["c"]=>
string(3) "cat"
["d"]=>
string(3) "dog"
["e"]=>
string(8) "elephant"
}
array(5) {
["a"]=>
string(5) "apple"
["b"]=>
string(4) "ball"
["c"]=>
string(3) "cat"
["d"]=>
string(3) "dog"
["e"]=>
string(8) "elephant"
}
That’s it for now. You can explore more functions related to JSON in php.net documentation. If you have any questions related to this tutorial then feel free to let me know in the comments.