Home Backend Development PHP Tutorial How To Parse JSON With PHP

How To Parse JSON With PHP

Jun 23, 2016 pm 02:31 PM

Parsing a JSON file or string is just as easy as parsing XML once you get the syntax, and in this tutorial I’ll show you how to parse and learn its syntax. But before we begin let’s establish some naming conventions for PHP arrays just in case you don’t know them already.




Take a look at the following PHP array.

$arrayName[key]=value;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Arrays in PHP have three parts, the name or variable used, the key ( can be associative or numeric) and the value of that key.

When we read/parse a json string or file with PHP what we will be doing is basically assigning a bunch of keys to a variable and so that variable will become an associative array. In case you haven’t heard the terms associative or numeric, numeric simply means that you are using numbers as keys.

Now that we got a convention let’s look at a simple JSON string.

$string='{"name":"John Adams"}';
Copy after login

You can think of this string as a key “name” that holds the value “John Adams”. Notice the brackets, they are used to separate arrays of keys. So we can give the following naming convention to this json string

{"key":"value"}
Copy after login

To parse JSON with PHP we will be using the funcion json_decode , this function takes a json string for its first parameter and an optional boolean (true/false) for its second parameter. The second parameter, if set to true, returns the json string as an associative array, if it’s not set it will return an object. The main difference between the two options is the syntax you use to refer to keys, for now we’ll be setting the second parameter to true so that it returns the more familiar associative array, but we will cover objects.

Now that you know about this new function make your php file look like mine.

$string='{"name":"John Adams"}';$json_a=json_decode($string,true);
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Using json_decode with the second parameter set to true we have assigned an associative array to the variable $json_a, so $json_a is now an array. I use “_a” to refer to an associative array, we’ll later use $json_o to refer to a variable that holds the json as an object but you can use whatever variable name you want.

Let me translate the code above to a more familar and basic snippet that is doing the same thing.

$json_a=array("name"=>"John Adams");// or also$json_a["name"]="John Adams";
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Now it’s clear what you can do with “$json_a” right? To show contents of “name” you would simply echo $json_a[name] like this

echo $json_a[name];// and you should see the name John Adams printed on your browser.
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

That was easy, now let’s use the same json string but this time we won’t set the second parameter so that we can get an object. Fill your php file with the following code.

$string='{"name":"John Adams"}';$json_o=json_decode($string);
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

This time instead of returning an array, json_decode has returned an object. The word object might sound a little intimidating but believe me when I say this isn’t hard at all.

To show the contents of “name” all one has to do is this

echo $json_o->name;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Can you tell the difference between outputting $json_a and $json_o’s content? That’s right! the only difference is that with $json_o you get rid of the leading “]” and replace “[” with “->”.

echo $json_a[name];// andecho $json_o->name;// will both display “John Adams”
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

The json string we've been using is very simple so am going to make it a little more interesting. The content of your php file up to this point should be this

$string='{"name":"John Adams"}';// create object from string$json_o=json_decode($string);// create array from string$json_a=json_decode($string,true);
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Whenever I make changes to the value of your $string variable keep the last two lines with json_decode for the rest of this tutorial.

$string='{                     "name":"John Adams",                     "age":"40"                   }';$json_o=json_decode($string);$json_a=json_decode($string,true);
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

As you might guess from the the new way $string looks, you separate each set of keys and values with a comma. So to display to value of age, which is 40, you can use either of these two methods.

// associative array modeecho $json_a[age];// object modeecho $json_o->age;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

But this JSON string is still too simple, why don't we assign two keys to a key. Then new json string will be this.

$string='{                     "name":{"first":"John","last":"Adams"},                     "age":"40"                   }';
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

What we’ve done is we have separated the name “John Adams” into two "subkeys;” , first and last. We can display the values of these new keys this way.

// array method  // display first name echo  $json_a[name][first];  // display last name echo  $json_a[name][last];// object method  // display first name  echo $json_o->name->first;  // display last name  echo $json_o->name->last;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

So far so good. You have probably seen the symbols [ and ] used in json and if you haven't you will right now because that's what our new $string variable will include.

$string='[            {                "name":{"first":"John","last":"Adams"},                                "age":"40"            },            {                "name":{"first":"Thomas","last":"Jefferson"},                                "age":"35"            }         ]';
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

We use [ and ] to indicate that we have an array of keys, that is more than one set of { }'s. That means then, that this string has two arrays , each of them separated by { and } and followed by a comma except for the last one. This array is numeric, so to access "age" in the second array we'll do the following.

// remember that arrays start at zero, that's why we use 1 to refer to the second array// array methodecho $json_a[1][age];// object methodecho $json_o[1]->age;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

In your web development career you will encounter yet another type of json string.

$string='{"person":         [            {                "name":{"first":"John","last":"Adams"},                "age":"40"            },            {                "name":{"first":"Thomas","last":"Jefferson"},                "age":"35"            }         ]         }';
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

This string is just like the previous one except that we have added {"person": at the beginning and to close, we added a } at the end.

What we have here is two "person" arrays one for John and one for Thomas. You can display both last names with this snippet of code.

// array method     // first person "0"echo $json_a[person][0][name][last];    // second person "1"echo $json_a[person][1][name][last];// object method   // first person "0"echo $json_o->person[0]->name->last;  // second person "1"echo $json_o->person[1]->name->last;
Copy after login

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

It all seems fine, until we have a 100 "person" array or more! But don't worry. Because these arrays are numeric we can use a loop to go through a huge array like that. I like to use "foreach" loops but you can use "while", "for" or "do while" loops if you want. The next snippet will show you how you can get each person's information using a foreach loop.

$string='{"person":[            {                "name":{"first":"John","last":"Adams"},                "age":"40"            },            {                "name":{"first":"Thomas","last":"Jefferson"},                "age":"35"            }         ]}';$json_a=json_decode($string,true);$json_o=json_decode($string);// array methodforeach($json_a[person] as $p){echo 'Name: '.$p[name][first].' '.$p[name][last].'Age: '.$p[age].'';}// object methodforeach($json_o->person as $p){echo 'Name: '.$p->name->first.' '.$p->name->last.'Age: '.$p->age.'';}
Copy after login

Reading a JSON is just as easy and it does not have a special extension, the file just has to output a json string. To read a JSON file you can use the function file_get_contents like this $string=file_get_contents(filepath) . Now pass $string to json_decode and parse.

From:http://webhole.net/2009/08/31/how-to-read-json-data-with-php/

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles