Verification: a143cc29221c9be0

Parsing json string in php

Use file_get_contents() Function to Parse a JSON File in PHP

The built-in function file_get_contents() is used to read a file and store it into a string. By using this function, we can parse a JSON file to a string. The correct syntax to use this function is as follows.

file_get_contents($pathOfFile, $searchPath, $customContext, $startingPoint, $length);

This function accepts five parameters. The detail of these parameters is as follows.

Parameter Description
$pathOfFile mandatory It specifies the path of the file
$searchPath optional It specifies the path to search file.
$customContext optional It is used to specify a custom context.
$startingPoint optional It specifies the starting point of the reading file.
$length optional It is the maximum length of the file in bytes to be read.

The following program shows how to parse a JSON file.

The function file_get_contents() have only parsed the JSON data stored in a JSON file. We cannot use this data directly.

Output:

string(328) "[
    {
        "id": "01",
        "name": "Olivia Mason",
        "designation": "System Architect"
    },
    {
        "id": "02",
        "name": "Jennifer Laurence",
        "designation": "Senior Programmer"
    },
    {
        "id": "03",
        "name": "Medona Oliver",
        "designation": "Office Manager"
    }
]"

To make this data useful, we can use json_decode() to convert the JSON string to an array. Using this function in the below program.

Output:

array(3) {
  [0]=>
  array(3) {
    ["id"]=>
    string(2) "01"
    ["name"]=>
    string(12) "Olivia Mason"
    ["designation"]=>
    string(16) "System Architect"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(2) "02"
    ["name"]=>
    string(17) "Jennifer Laurence"
    ["designation"]=>
    string(17) "Senior Programmer"
  }
  [2]=>
  array(3) {
    ["id"]=>
    string(2) "03"
    ["name"]=>
    string(13) "Medona Oliver"
    ["designation"]=>
    string(14) "Office Manager"
  }
}

Contribute

DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.