How to process json data in php?

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. 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": "",
    "age": 77
}

We can read information from this JSON file by using the code below:

name;
// Monty

echo $decoded_json->email;
// 

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.

Now, we will decode JSON that is slightly more complicated and try to get back useful information from it.

{
    "name": "Monty",
    "email": "",
    "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.

Let's 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": "",
        "age": 62,
        "countries": [
          {
            "name": "Italy",
            "year": 1983
          },
          {
            "name": "Canada",
            "year": 1998
          },
          {
            "name": "Germany",
            "year": 2003
          }
        ]
      },
      {
        "name": "Sajal",
        "email": "",
        "age": 65,
        "countries": [
          {
            "name": "Belgium",
            "year": 1994
          },
          {
            "name": "Hungary",
            "year": 2001
          },
          {
            "name": "Chile",
            "year": 2013
          }
        ]
      },
      {
        "name": "Adam",
        "email": "",
        "age": 72,
        "countries": [
          {
            "name": "France",
            "year": 1988
          },
          {
            "name": "Brazil",
            "year": 1998
          },
          {
            "name": "Poland",
            "year": 2002
          }
        ]
      },
      {
        "name": "Monty",
        "email": "",
        "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.

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 the 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.

 $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 json_encode() function. 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.

 [
        ["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 the desired format. For example, you can use the JSON_PRETTY_PRINT flag to add 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 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.

 [
        ["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:

Final Thoughts

In this tutorial, you learned how to read JSON data from a file or string in PHP. You also learned how to convert that JSON into an array and traverse it to extract the information you 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.

Did you find this post useful?

How to process json data in php?

Freelancer, Instructor

I am a full-stack developer who also loves to write tutorials. After trying out a bunch of things till second year of college, I decided to work on my web development skills. Starting with just HTML and CSS, I kept moving forward and gained experience in PHP, JavaScript and Python. I usually spend my free time either working on some side projects or traveling around.

How do I extract data from JSON with PHP?

Use json_decode() Function to Extract Data From JSON in PHP. We will use the built-in function json_decode() to extract data from JSON. We will convert the JSON string to an object or an array to extract the data. The correct syntax to use this function is as follows.

How are JSON values accessed in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.

Can JSON be used with PHP?

The json_encode function returns the JSON representation of the given value. The json_decode takes a JSON encoded string and converts it into a PHP variable. PHP frameworks such as Symfony and Laravel have built-in methods that work with JSON.

How can access JSON decoded data in PHP?

PHP and JSON.
The json_encode() function is used to encode a value to JSON format..
The json_decode() function is used to decode a JSON object into a PHP object or an associative array..
The json_decode() function returns an object by default. ... .
You can also loop through the values with a foreach() loop:.