EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP json_decode

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP json_decode

PHP json_decode

Introduction to PHP json_decode

In PHP the inbuilt function json_decode() function is defined as a function as it name suggest it is a function for conversion of any JSON a standard text format objects or decoding of JSON objects to PHP objects, taking a JSON string as a parameter which this function converts or decodes it and returns the encoded values which were in JSON into proper PHP objects. In general, the PHP provides a function that takes a JSON string that usually represents a javascript array or object literals for converting this encoded string in JSON format to a particular PHP object data type.

Working of Json_decode() in PHP

In this article, json_decode() is an inbuilt function provided by PHP for converting or decoding the JSON string into PHP objects where this function takes the JSON data or string which represented as a javascript array as a parameter which is an encoded string is decoded to PHP objects or data types using this json_decode() function and the opposite is done using json_encode() function in PHP.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In the below section we will see syntax and examples of using the json_decode() function:

Syntax:

json_decode(json_string, asso_arr, recur_depth, opt)

Parameters:

Json_string: this parameter is compulsory to specify the JSON encoded string for converting it into PHP objects

  • Asso_arr: this parameter is used to specify the Boolean values that can return an associated array if the value is set to true, else returns an object if it is set to false. This parameter is optional and has false as the default value.
  • Recur_depth: this parameter is used to specify the depth of the recursion and this is also an optional parameter with 512 as a default value.
  • Opt: this parameter is used to specify the bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,JSON_INVALID_UTF8_SUBSTITUTE, JSON_THROW_ON_ERROR and this also an optional parameter.

This json_decode() function of PHP takes JSON encoded string as input and returns the value that is decoded to PHP objects which of PHP data types and if the decoding is not possible then this function returns null instead of PHP objects. Now let us see simple example which uses json_decode() of PHP in a HTML structure.

Examples of PHP json_decode

Following are the examples are given below:

Example #1

Code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Educba- PHP json_decode</title>
</head>
<body>
<?php
$json_string = '{
"CompayName": "Educba",
"Director": "Snehal",
"Employee": "Amardeep",
"address": {
"ColonyName": "Shivaji road",
"city": "Baramati",
"state": "Maharashtra",
"postalCode": "1234567"
},
"TelephoneNumbers": [
{ "type": "Work", "phonenumber": "9876543210" }
] }';
var_dump(json_decode($json_string, true));
?>
</body>
</html>

Output:

PHP json_decode-1.1

In the above program, we can see when we are writing PHP code in HTML structure we start with “< ?php” then we write the code and at the end the closing tag for PHP code is “? >”. In the above code, we can are declaring a JSON variable as json_string in which we are storing the JSON format data to be converted and then this variable is passed as a parameter to json_decode() function with asso_arr set as “true” that gives it in an array format as shown in the above screenshot. It has array(5) which means it has 5 elements in an array. Suppose we have not set anything or not passed asso_arr parameter such as “var_dump(json_decode($json_string));” then this value would give us access to the property of the object in an array as shown in the below screenshot.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,678 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

PHP json_decode-1.2

Now we will see an example below having an invalid JSON format and passing this string to the json_decode() function and what error and output it will give and we will also how to print those array which can be accessed using the “echo” function in the below section.

Example #2

In the below program we will see how to access an element of an array using the echo function.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Educba- PHP json_decode</title>
</head>
<body>
<?php
$json_string = '[
{
"Companyname": "Educba",
"Director": "Snehal",
"phnumber": "89945954874"
},
{
"Companyname": "Google",
"Director": "Ann",
"phnumber": "9877564694"
}
]';
$x = json_decode($json_string);
echo $x[0]->Companyname;
?>
</body>
</html>

Output:

Output-1.3

In the above program, we can see when we have declared a json_string and access any of element in array we use array[index] in any programming language similarly, we write it with echo function and in the above code we have to observe that we have not passed asso_arr parameter in the json_decode() function so to access the element we have to write “echo $x[0]-> Companyname;” and if we set the second parameter to “true” then we have to write “echo $x[0][‘Companyname’];”.

Example #3

In the below, we will see passing an invalid JSON string to the function and try printing the errors also.

Code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Educba- PHP json_decode</title>
</head>
<body>
<?php
$json_string = '[
{
"Companyname": "Educba"
"Director": "Snehal"
"phnumber": "89945954874"
"Companyname": "Google"
"Director": "Ann"
"phnumber": "9877564694"
}
]';
$x = json_decode($json_string);
echo $x[0]->Companyname;
echo json_last_error();
echo json_last_error_msg();
?>
</body>
</html>

Output:

Output-1.4

In the above program, we can see in the variable “json_string” we have passed an invalid JSON data and we are trying to access the object in the above JSON string to PHP object when it is converted using json_decode() function. Then we are even printing json_last_error() and json_last_error_msg() functions which will print about the error information such as “4 syntax error” that is related to the PHP code written in the above example with the screenshot shown above and if we do not want to print any of error messages using the error functions then the output would be “null” that means it will not print anything in the converted objects of PHP as JSON string or data itself is invalid and this can be seen in the below screenshot.

Output-1.5

Conclusion

In this article, we conclude that the PHP provides a json_decode() function that is defined as a function for converting or decoding any JSON format string or data into the PHP data type objects as output. In this article we saw how to define or declare the function json_decode() along with its syntax and parameters are explained. Then in the next section, we saw an example of how it will print the arrays if the asso_arr is set to true and false (by default). Then we also saw how to access the array elements and lastly, we also saw what will be the error or what it will print in the output if we have passed an invalid JSON string or data.

Recommended Articles

This is a guide to PHP json_decode. Here we also discuss the introduction and working of json_decode() in PHP along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. PHP Global Variable
  2. PHP delete file
  3. PHP count
  4. PHP usort()

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More