Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is PHP?
3.
What is JSON?
3.1.
Syntax:
4.
How To Use JSON In PHP?
4.1.
json_encode()
4.2.
json_decode()
5.
How To Access The Decoded Values in PHP?
6.
How to Create Loops With The Decoded Values
7.
Parsing And Generating A JSON File In PHP
8.
Frequently Asked Questions
8.1.
How to create PHP JSON?
8.2.
How to post JSON data in PHP?
8.3.
How to pass data through JSON in PHP?
9.
Conclusion
Last Updated: Sep 27, 2024

PHP and JSON

Author Ranjul Arumadi
2 upvotes

Introduction

PHP and JSON are used widely by developers to develop interactive and dynamic websites. PHP, short for Hypertext Preprocessor, is a simple scripting language developers use to build websites. PHP could be inserted into HTML code, enabling us to develop websites with additional functionalities without calling external files for data. 

 

JSON stands for JavaScript Object Notation. JSON is easy to learn and understand as it is self-describing. JSON is a lightweight format that is used to store and transport data. JSON is used to transmit data from a server to a webpage.

 

PHP has many functions to handle JSON effectively. PHP and JSON go hand in hand. In this blog, we are discussing PHP and JSON. 

What is PHP?

PHP is a widely used open-source scripting language. PHP scripts are interpreted on a server that has PHP installed. PHP files can incorporate text, HTML, CSSJavaScript, and PHP codes. PHP will execute a PHP file on the server, and the file will return its result to the browser as plain HTML. We can create PHP files by using the ".php" file extension. Developers prefer to use PHP for a variety of reasons, including the following:

 

  • PHP supports a wide range of databases.
  • PHP is free and open-source.
  • PHP is compatible with almost all the servers used today (like IIS, Apache, etc.)
  • We can run PHP on various platforms like Linux, Unix, Windows, Mac OS X,  etc.
  • PHP is easy to learn and understand.
  • PHP runs efficiently on the server-side.

 

We can place a PHP script anywhere in the file. To use PHP script, we must use the following syntax:

<?php
  // The PHP code should be written here
?>
You can also try this code with Online PHP Compiler
Run Code

 

Let us take the example of printing a sentence using PHP to understand this better.

<!DOCTYPE html>
<html>
<body>
<p>Hello there!</p>
<?php
echo "This is an example showing PHP syntax.";
?>
</body>
</html>

 

Output:

What is JSON?

JSON is used for storing and exchanging data. JSON data is written as a pair of keys and their corresponding value. JSON is short, easy to understand, and quicker to read and write. JSON can also use arrays.

 

Syntax:

{
“Data”:[{
 “key”:”value”,
“key”:”value”,
“key n”:”value”
},
…
…
{
“key”:”value”,
“key”:”value”,
“key n”:”value”
}]
}

 

The example of JSON notation is as follows:

{
"Student":[{
"Name":"Snigdha",
"Age":15,
},
{
"Name":"Ranjul",
"Age":23,
}]
}

How To Use JSON In PHP?

Like XML (Extensible Markup Language), JSON is a text-based format that's easy to write and easy to understand, but unlike XML, JSON data structures occupy less bandwidth than their XML versions. To use JSON with PHP, we have to utilize the built-in functions in PHP that can handle JSON. PHP allows us to encode and decode JSON with the help of two functions: json_encode() and json_decode(). 

json_encode()

This function is used to encode a value into JSON format. The value encoded can be any PHP data type except a resource (like a Database). 

 

Let us consider an example

<?php
$age = array("Snigdha"=>15, "Ranjul"=>23, "Joshua"=>52);
echo json_encode($age);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

 

Here, “age” is an array consisting of names of people and their ages. Using json_encode($age), we have converted it into JSON format. 

json_decode()

This function converts a JSON encoded string into an appropriate PHP data type. In other words, the json_decode() function decodes a JSON object into a PHP object or an associative array.

 

By default, the json_decode() function returns a PHP object. When a second parameter is included and set as “true”, JSON objects are converted to an associative array. The following examples demonstrate the usage of json_decode().

 

The JSON data is converted to a PHP object in the example given below.

<?php
$jsonobj = '{"Snigdha":15,"Ranjul":23,"Joshua":52}';
var_dump(json_decode($jsonobj));
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

 

In the example given below, the JSON data is converted into an associative array.

<?php
$jsonobj = '{"Snigdha":15,"Ranjul":23,"Joshua":52}';
var_dump(json_decode($jsonobj,true));
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

How To Access The Decoded Values in PHP?

Now that we have learnt to encode to JSON format and decode a JSON object let us see how we can access the values once a JSON object is converted to a PHP object or an associative array.

 

Let us look at an example to see how to access values from a PHP object.

<?php
$jsonobj = '{"Snigdha":15,"Ranjul":23,"Joshua":52}';
$obj = json_decode($jsonobj);
echo "Roll no: ".$obj->Snigdha."<br>";
echo "Roll no: ".$obj->Ranjul."<br>";
echo "Roll no: ".$obj->Joshua."<br>";
?>
You can also try this code with Online PHP Compiler
Run Code

 

The following example shows us how to access values from an associative array.

<?php
$jsonobj = '{"Snigdha":15,"Ranjul":23,"Joshua":52}';
$arr = json_decode($jsonobj, true);
echo "Roll no: ".$arr["Snigdha"]."<br>";
echo "Roll no: ".$arr["Ranjul"]."<br>";
echo "Roll no: ".$arr["Joshua"]."<br>";
?>
You can also try this code with Online PHP Compiler
Run Code

 

 The output of both of the code snippets are the same.

How to Create Loops With The Decoded Values

Looping is one of the most fundamental concepts commonly used by programmers. Loops are programming structures where some instructions in the code are repeated until the specific condition is satisfied. 

 

To understand this, let’s take an example of searching for a number, N, given by the user from a list of seven numbers; instead of writing seven instructions to compare N with each of the seven numbers, the programmer could use a loop with a looping variable and one instruction inside the loop which would compare the number N with each of the seven numbers. 

 

We can use loops with these values after the JSON string is decoded and accessed. We use the foreach() function to loop the accessed values. To see how it works, let us take a look at the following examples:

 

  • Looping the values of a PHP object
<?php
$jsonobj = '{"Snigdha":15,"Ranjul":23,"Joshua":52}';
$obj = json_decode($jsonobj);
foreach($obj as $key => $value) {
 echo $key . "'s age is " . $value . "<br>";
}
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

  • Looping the values of an associative array
<?php
$jsonobj = '{"Snigdha":15,"Ranjul":23,"Joshua":52}';
$arr = json_decode($jsonobj,true);
foreach($arr as $key => $value) {
 echo $key . "'s age is " . $value . ".<br>";
}?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

Parsing And Generating A JSON File In PHP

Parsing a JSON file in PHP means using a JSON file inside a PHP script. Generating a JSON file from a PHP script means creating a JSON file from the PHP objects and arrays used in the PHP file. To parse and generate a JSON file in PHP, we will have to use the functions file_get_contents() and file_put_contents().   The syntaxes are:

file_get_contents(path, file_name)
You can also try this code with Online PHP Compiler
Run Code

 

This function is used to read the entire file to a string.

 

Parameters

  • The “file_name” is the name of the file.
  • The “path” is the location to be checked for the JSON file.

 

We have to use the json_decode() function to decode the JSON file into an array to display.

 

For example, consider the following code.

<?php
$json = file_get_contents('my_file.json');
$json_arr = json_decode($json,true);
// Display data
print_r($json_arr);
?>
You can also try this code with Online PHP Compiler
Run Code

 

We would parse the file’s contents “my_file.json” using this PHP script. Then we used the json_decode() to decode the JSON objects to an associative array, and we finally displayed it.

 

file_put_contents(file_name.json.json_object)
You can also try this code with Online PHP Compiler
Run Code

 

This function is used to write data to a file.

 

Parameters

  • The “file_name” is the name of the JSON file to be saved.
  • The “json_object” is the object created after the JSON from the array is created.

 

For example, consider the code given below.

<?php
$array = Array (
   "0" => Array (
       "name" => "Snigdha",
       "age" => "15"
   ),
   "1" => Array (
       "name" => "Ranjul",
       "age" => "23"
   )
);
$json = json_encode($array);
// Display it
echo "$json";
file_put_contents("my_file1.json", $json);
?>
You can also try this code with Online PHP Compiler
Run Code

 

Output:

We created an array and encoded it to JSON format using json_encode(). Then we displayed and used the file_put_contents() function to generate a JSON file named “my_file1.json”. 

Frequently Asked Questions

How to create PHP JSON?

To create JSON in PHP, use the json_encode() function. This function converts PHP arrays or objects into JSON-formatted strings, enabling data interchange between the server and client.

How to post JSON data in PHP?

To post JSON data in PHP, use cURL or similar methods to send HTTP POST requests with JSON as the payload. Decode the JSON in PHP using json_decode() on the receiving end.

How to pass data through JSON in PHP?

To pass data through JSON in PHP, encode your data with json_encode(), then send it via an HTTP request or store it for later use. The receiver can decode this JSON string back into PHP data with json_decode().

Conclusion

In this blog, we have looked at PHP and JSON. PHP is a scripting language used by developers to develop dynamic websites, and JSON is used to store and transport data. Both PHP and JSON are easy to learn and understand. We can use PHP and JSON together to create websites. 

 

To parse a JSON file in PHP, we must use the function file_get_contents(). To generate a JSON file from a PHP object or an array, we use the function file_put_contents(). The json_encode() is used to convert a PHP datatype to JSON format whereas json_decode() is used to convert a JSON object to an appropriate PHP datatype. We also learned about how the decoded values are accessed inside PHP. We could also loop the JSON values decoded and accessed in the PHP file. Looping of such values is done in PHP with the help of the foreach() function.

 

If you loved reading this article about PHP And JSON, check out Why Use PHP programming in 2021? Its Pros and Cons and 5 Best Free PHP Projects With Source Code To Work In 2021.

Live masterclass