By Team Escalera
on 31 Oct 2017 02:41 PM
  • Php training in lucknow
0 comments

JSON (JavaScript Object Notation) is a lightweight data-interchange format.

Let’s have a look at an example JSON Output (From Railway API)

“TRAIN_NUM”: “12429”,

“FROM_STATION”: {

        “CODE”: “LKO”,

        “NAME”: “LUCKNOW”

    },

“ERROR”: FALSE,

“TRAIN_NAME”: “LKO NDLS AC SF”,

“TO_STATION”: {

        “CODE”: “NDLS”,

        “NAME”: “NEW DELHI”

THIS AS A STRUCTURED DATA WITH  PARAMETER NAMES.

For eg.  If we want to return the train name from this data the output will be: LKO NDLS AC SF

Compare the JSON with :

{“key”:”value”}

Hence “train_name” will be the “key” in our case and “LKO NDLS AC SF” will be the “value”

The Php File

<?php

$str = file_get_contents(‘example.json’);

//Here Example.json is the name of Json file stored in the same directory in which our php file is stored

$json = json_decode($str, true);

//JSON_DECODE function considers the json string for its first parameter and an optional boolean (true/false) for its second parameter.

// If we want the json string as an associative array the second parameter is set to true.

echo ‘Train Name =’ .  $json[‘train_name’];

echo ‘Train Num = ‘. $json[‘train_num’];

echo ‘From ‘Station = ‘. $json[‘from_station’][‘name’];

echo ‘To Station = ‘.$json[‘to_station’][‘name’];

//We can return from / to station Code As Well.

Comments (0)

Leave A Comment