Monday, October 28, 2013

How To Read JSON Data Response Using PHP?

This tutorial will teach you how to decode JSON objects using PHP. Reading a JSON is just as easy and it just has to output a json string and save it to variable(for instance $json_data), And now pass $json_data to json_decode function and read/parse.
Example JSON Response
$json_data = '{
      "stat": "ok",
      "profile": {
        "providerName": "testing",
        "identifier": "",
        "displayName": "testing 1",
        "preferredUsername": "testing 2",
        "name": {
          "formatted": "testing"
        "url": "",
        "photo": "",
        "providerSpecifier": "testing"
PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from json to appropriate PHP type. The following examples shows how PHP can be used to decode JSON objects:
Alternative 1 (returns object format)
$data = json_decode($json_data);
echo $data->profile->displayName; // outputs testing 1
echo $data->profile->preferredUsername;// outputs testing 2
Alternative 2 (returns array format)
$data = json_decode($json_data, true);
$preferredUsername = $data['profile']['preferredUsername'];
$displayName = $data['profile']['displayName'];

No comments:

Post a Comment