JSON, short for JavaScript Object Notation, is a common lightweight format for storing and exchanging information. As the name suggests, it was initially derived from JavaScript but it is a language-independent format for storing information. A lot of languages like PHP now implement functions to read and create JSON data.
This tutorial will teach you how to read a JSON file and convert it to an array in PHP. Learn how to parse JSON using the json_decode()
and json_encode()
functions.
Reading JSON From a File or String in PHP
Let's say you have a file which contains information in JSON format. How do you access and store it in PHP?
First, you need to get the data from the file into a variable by using file_get_contents()
. Once the data is in a string, you can call the json_decode()
function to extract information from the string. Keep in mind that JSON simply provides a way to store information as a string using a set of predefined rules. It is our job to decode the strings properly and get the information we want.
The json_decode()
function accepts four parameters but you will only need the first two in most situations. The first parameter specifies the string that you want to decode. The second parameter determines how the decoded data is returned back. Setting it to true
will return an associative array and false
will return objects. Here is a basic example. We have a file called people.json with the following contents:
{ "name": "Monty", "email": "monty@something.com", "age": 77 }
We can read information from this JSON file by using the code below:
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, false); echo $decoded_json->name; // Monty echo $decoded_json->email; // monty@something.com echo $decoded_json->age; // 77 ?>
In the above example, json_decode()
returned an object because the second parameter was set to false
. You can set it to true
to get the data back as an associative array.
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, true); echo $decoded_json['name']; // Monty echo $decoded_json['email']; // monty@something.com echo $decoded_json['age']; // 77 ?>
Now, we will decode JSON that is slightly more complicated and try to get back useful information from it.
{ "name": "Monty", "email": "monty@something.com", "age": 77, "countries": [ {"name": "Spain", "year": 1982}, {"name": "Australia", "year": 1996}, {"name": "Germany", "year": 1987} ] }
Our goal is to get back all the countries visited by the person in different years. The value returned by $decoded_json['countries']
will actually be an array and we will loop through it like regular arrays to get our data.
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, true); $name = $decoded_json['name']; $countries = $decoded_json['countries']; foreach($countries as $country) { echo $name.' visited '.$country['name'].' in '.$country['year'].'.'; } /* Monty visited Spain in 1982. Monty visited Australia in 1996. Monty visited Germany in 1987. */ ?>
Lets go over just one last example of extracting information from a JSON file. Here is the JSON from which we will extract our data.
{ "customers": [ { "name": "Andrew", "email": "andrew@something.com", "age": 62, "countries": [ { "name": "Italy", "year": 1983 }, { "name": "Canada", "year": 1998 }, { "name": "Germany", "year": 2003 } ] }, { "name": "Sajal", "email": "sajal@something.com", "age": 65, "countries": [ { "name": "Belgium", "year": 1994 }, { "name": "Hungary", "year": 2001 }, { "name": "Chile", "year": 2013 } ] }, { "name": "Adam", "email": "adam@something.com", "age": 72, "countries": [ { "name": "France", "year": 1988 }, { "name": "Brazil", "year": 1998 }, { "name": "Poland", "year": 2002 } ] }, { "name": "Monty", "email": "monty@something.com", "age": 77, "countries": [ { "name": "Spain", "year": 1982 }, { "name": "Australia", "year": 1996 }, { "name": "Germany", "year": 1987 } ] } ] }
We have two nested arrays in the JSON data this time. So, we will be using two nested loops to get the countries visited by different customers.
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, true); $customers = $decoded_json['customers']; foreach($customers as $customer) { $name = $customer['name']; $countries = $customer['countries']; foreach($countries as $country) { echo $name.' visited '.$country['name'].' in '.$country['year'].'.'; } } /* Andrew visited Italy in 1983. Andrew visited Canada in 1998. Andrew visited Germany in 2003. Sajal visited Belgium in 1994. Sajal visited Hungary in 2001. Sajal visited Chile in 2013. Adam visited France in 1988. Adam visited Brazil in 1998. Adam visited Poland in 2002. Monty visited Spain in 1982. Monty visited Australia in 1996. Monty visited Germany in 1987. */ ?>
You should now have a rough idea of the approach you should take to read JSON data from a file depending on how it has been created.
Reading JSON Data Without Knowing Keys Beforehand
So far we have read JSON data where we already knew all the keys. That might not always be true. Luckily, we can still extract useful information from the file once we have stored it as an associative array. The following example should clear things up.
{ "kdsvhe": { "name": "Andrew", "age": 62 }, "lvnwfd": { "name": "Adam", "age": 65 }, "ewrhbw": { "name": "Sajal", "age": 72 }, "klkwcn": { "name": "Monty", "age": 77 } }
The keys in the above JSON seem to be random strings that we cannot predict beforehand. However, once we convert it into an associative array we will no longer need to know the exact key values to iterate through the data.
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, true); foreach($decoded_json as $key => $value) { $name = $decoded_json[$key]["name"]; $age = $decoded_json[$key]["age"]; echo $name.' is '.$age.' years old.'; } /* Andrew is 62 years old. Adam is 65 years old. Sajal is 72 years old. Monty is 77 years old. */ ?>
Creating JSON Data in PHP
You can also turn your own data into a well formatted JSON string in PHP with the help of the function json_encode()
. It basically accepts three parameters but you will usually only need the first one i.e., the value you want to encode in most situations.
<?php $people_info = [ "customers" => [ ["name" => "Andrew", "score" => 62.5], ["name" => "Adam", "score" => 65.0], ["name" => "Sajal", "score" => 72.2], ["name" => "Monty", "score" => 57.8] ] ]; echo json_encode($people_info); /* {"customers":[{"name":"Andrew","score":62.5},{"name":"Adam","score":65},{"name":"Sajal","score":72.2},{"name":"Monty","score":57.8}]} */ ?>
You might also need to use some flags in order to get the JSON string in desired format. For example, the JSON_PRETTY_PRINT
flag can be used to add white space for proper formatting of JSON string. Similarly, you can use the JSON_PRESERVE_ZERO_FRACTION
flag to make sure float values are always stored as floats even if they are equivalent to some integer in magnitude. You can see a list of all such flags in the official documentation.
<?php $people_info = [ "customers" => [ ["name" => "Andrew", "score" => 62.5], ["name" => "Adam", "score" => 65.0], ["name" => "Sajal", "score" => 72.2], ["name" => "Monty", "score" => 57.8] ] ]; echo json_encode($people_info, JSON_PRETTY_PRINT|JSON_PRESERVE_ZERO_FRACTION); /* { "customers": [ { "name": "Andrew", "score": 62.5 }, { "name": "Adam", "score": 65.0 }, { "name": "Sajal", "score": 72.2 }, { "name": "Monty", "score": 57.8 } ] } */ ?>
Dealing with Errors During Encoding and Decoding
The JSON format requires us to follow a specific set of rules for proper encoding and decoding of the strings. For example, names and values should be enclosed in double quotes and there should be no trailing comma after name-value pairs. The json_last_error_msg()
function can help you figure out what kind of error you are getting so that you can take appropriate steps. Here is a very basic example:
<?php $sample_json = '{"name": "value", }'; var_dump(json_decode($sample_json)); // NULL echo json_last_error_msg(); // Syntax error ?>
Final Thoughts
In this tutorial, you learned how to read JSON data from a file or string in PHP. We also learned how to convert that JSON into an array and traverse it to extract the information we want. You should now be able to get information from JSON in a file where you don't know all the keys in key-value pairs. In the last two sections, we covered how you can stringify data as JSON in PHP and the errors you might encounter during the encoding and decoding process.
Hopefully, this will answer all your questions about encoding and decoding JSON in PHP.
No comments:
Post a Comment