Reading Json File Line by Line Php
Read Time: 7 mins Languages:
JSON, short for JavaScript Object Notation, is a common lightweight format for storing and exchanging information. As the proper name suggests, information technology was initially derived from JavaScript, merely it is a language-independent format for storing information. A lot of languages similar PHP at present implement functions to read and create JSON information.
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
Permit's say you have a file which contains information in JSON format. How exercise you access and store it in PHP?
Kickoff, you need to become the data from the file into a variable by using file_get_contents()
. Once the data is in a cord, you can telephone call the json_decode()
function to extract information from the cord. Keep in listen that JSON simply provides a style to store information as a string using a set of predefined rules. Information technology is our job to decode the strings properly and get the data we desire.
The json_decode()
function accepts four parameters, only you will just need the first two in most situations. The outset parameter specifies the string that you desire to decode. The 2d parameter determines how the decoded information is returned. Setting it to true
will return an associative array, and false
volition return objects. Here is a basic instance. We have a file chosen people.json with the post-obit contents:
{ "proper name": "Monty", "e-mail": "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, simulated); echo $decoded_json->name; // Monty repeat $decoded_json->email; // monty@something.com repeat $decoded_json->age; // 77 ?>
In the above example, json_decode()
returned an object considering the second parameter was prepare to false
. You can prepare it to true
to go the data dorsum as an associative array.
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, truthful); echo $decoded_json['name']; // Monty repeat $decoded_json['email']; // monty@something.com echo $decoded_json['age']; // 77 ?>
At present, we will decode JSON that is slightly more than complicated and try to become back useful information from it.
{ "proper noun": "Monty", "email": "monty@something.com", "age": 77, "countries": [ {"proper name": "Spain", "year": 1982}, {"name": "Australia", "year": 1996}, {"proper noun": "Germany", "year": 1987} ] }
Our goal is to get back all the countries visited by the person in dissimilar years. The value returned past $decoded_json['countries']
volition actually be an array, and we will loop through information technology like regular arrays to get our data.
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, true); $proper noun = $decoded_json['proper noun']; $countries = $decoded_json['countries']; foreach($countries every bit $land) { echo $name.' visited '.$country['name'].' in '.$country['year'].'.'; } /* Monty visited Spain in 1982. Monty visited Australia in 1996. Monty visited Germany in 1987. */ ?>
Let's get over just i 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": "Italian republic", "twelvemonth": 1983 }, { "name": "Canada", "year": 1998 }, { "name": "Germany", "year": 2003 } ] }, { "name": "Sajal", "email": "sajal@something.com", "age": 65, "countries": [ { "proper noun": "Belgium", "year": 1994 }, { "proper name": "Hungary", "year": 2001 }, { "name": "Chile", "year": 2013 } ] }, { "name": "Adam", "email": "adam@something.com", "age": 72, "countries": [ { "name": "France", "year": 1988 }, { "proper name": "Brazil", "twelvemonth": 1998 }, { "name": "Poland", "year": 2002 } ] }, { "proper noun": "Monty", "email": "monty@something.com", "age": 77, "countries": [ { "name": "Spain", "year": 1982 }, { "name": "Commonwealth of australia", "year": 1996 }, { "name": "Germany", "yr": 1987 } ] } ] }
We accept two nested arrays in the JSON data this time. So we will exist 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) { $proper noun = $customer['name']; $countries = $customer['countries']; foreach($countries as $land) { echo $proper noun.' visited '.$country['proper noun'].' in '.$country['year'].'.'; } } /* Andrew visited Italy in 1983. Andrew visited Canada in 1998. Andrew visited Federal republic of germany in 2003. Sajal visited Belgium in 1994. Sajal visited Republic of hungary in 2001. Sajal visited Republic of chile in 2013. Adam visited France in 1988. Adam visited Brazil in 1998. Adam visited Poland in 2002. Monty visited Kingdom of spain in 1982. Monty visited Commonwealth of australia in 1996. Monty visited Germany in 1987. */ ?>
You should at present have a rough thought of the approach you should accept to read JSON data from a file depending on how it has been created.
Reading JSON Data Without Knowing the Keys Beforehand
So far we take read JSON information where we already knew all the keys. That might not always exist true. Luckily, we tin nonetheless extract useful information from the file once nosotros have stored information technology every bit an associative array. The following example should clear things upwardly.
{ "kdsvhe": { "proper noun": "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 catechumen it into an associative assortment, we will no longer need to know the exact primal values to iterate through the data.
<?php $people_json = file_get_contents('people.json'); $decoded_json = json_decode($people_json, true); foreach($decoded_json every bit $key => $value) { $name = $decoded_json[$fundamental]["name"]; $age = $decoded_json[$key]["age"]; repeat $proper noun.' is '.$historic period.' years former.'; } /* Andrew is 62 years one-time. Adam is 65 years old. Sajal is 72 years quondam. Monty is 77 years old. */ ?>
Creating JSON Data in PHP
You tin can too turn your ain data into a well-formatted JSON string in PHP with the aid of the json_encode()
function. It basically accepts three parameters, but you will normally only need the first one, i.e. the value y'all desire to encode in most situations.
<?php $people_info = [ "customers" => [ ["name" => "Andrew", "score" => 62.v], ["proper 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.v},{"name":"Adam","score":65},{"name":"Sajal","score":72.two},{"proper noun":"Monty","score":57.8}]} */ ?>
Yous might also need to utilise some flags in guild to become the JSON cord in the desired format. For instance, y'all can employ the JSON_PRETTY_PRINT
flag to add together white space for proper formatting of the JSON string. Similarly, you can use the JSON_PRESERVE_ZERO_FRACTION
flag to make sure float values are e'er stored as floats, fifty-fifty 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.five], ["proper noun" => "Adam", "score" => 65.0], ["proper 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 united states to follow a specific set of rules for proper encoding and decoding of the strings. For example, names and values should exist enclosed in double quotes, and there should be no trailing comma after name-value pairs. The json_last_error_msg()
role tin can assist y'all figure out what kind of error you are getting and so that you can take appropriate steps. Here is a very bones example:
<?php $sample_json = '{"proper noun": "value", }'; var_dump(json_decode($sample_json)); // Aught 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. Y'all also learned how to convert that JSON into an array and traverse information technology to extract the data y'all want. Yous should at present be able to become 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 tin stringify information as JSON in PHP and the errors you lot might encounter during the encoding and decoding process.
Hopefully, this will answer all your questions about encoding and decoding JSON in PHP.
Source: https://code.tutsplus.com/tutorials/how-to-parse-json-in-php--cms-36994
0 Response to "Reading Json File Line by Line Php"
Post a Comment