Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Parsing a JSON file

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Parsing a JSON file

Postby mrashi12 » Mon Jul 14, 2014 9:56 am

Hi, As I am new to PHP and JSON my Interest in the field pushes me to know further. I have successfully parsed a JSON file:
{
"birthdays": [
"319507200" :"Kyle",
"1390435200" :"Noah",
"307843200" :"Carla"
]
}
Using this PHP file:
<?php
$jsondata = file_get_contents("birthdays.json");
$json = json_decode($jsondata,true);
echo $json["birthdays"][0]['1390435200'];
?>

Now I would like to know how to display when Noah’s birthday is, in the form yyyy/MM/dd. Can an expert tell me how this would be done?

Thank you :-)
mrashi12
New php-forum User
New php-forum User
 
Posts: 1
Joined: Mon Jul 14, 2014 9:47 am

Re: Parsing a JSON file

Postby kladrian » Thu Aug 14, 2014 10:56 am

Hi

first of all your json is not correct. You can't create an key/value array, that would be an object. So instead of [..] you've to use {}

here the correct json:
Code: Select all
{
    "birthdays": {
        "307843200": "Carla",
        "319507200": "Kyle",
        "1390435200": "Noah"
    }
}


then the code it's easy:

Code: Select all
try{
   $json = json_decode($jsondata);
   if (empty($json)){
      echo "invalid json";
      return;
   }
   $birthday = NULL;
   // try to find Noah's birthday
   foreach ($json->birthdays as $timestamp => $name) {
      if (strtolower($name) == 'noah') {
         $birthday = $timestamp;
         break;
      }
   }

   if (!empty($birthday)) {
      echo "Noah's birthday is " . date('Y/m/d');
   }
   else {
      echo "sorry, can't find Noah's birthday";
   }
}
catch (Exception $ee) {
   echo "failed to parse json file";
}


ask again if you need me to explain it :)

---
kladrian
kladrian
New php-forum User
New php-forum User
 
Posts: 12
Joined: Thu Aug 14, 2014 1:13 am


Return to PHP coding => General

Who is online

Users browsing this forum: No registered users and 1 guest

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.