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

Parsing Data

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Parsing Data

Postby olliemitch » Mon Jul 14, 2014 4:37 am

Hi,

I have a string that looks like this:

{
"cmd": "VarReturn",
"name": "temperature",
"result": 947,
"coreInfo": {
"last_app": "",
"last_heard": "2014-07-14T11:46:17.865Z",
"connected": true,
"deviceID": "234y8172390dfsa"
}
}

which I have fetched from a web page using file_get_contents();

How do I put the data into variables? Either a variable for each piece of data eg $cmd = "VarReturn", $name="temperature" or into an array?

At the moment I'm doing it the very messy way of using strpos() to look for each section, but I'm fairly sure there's a much easier way (using regular expressions?) but I'm a bit stuck on where to start.

Any help would be much appreciated.
olliemitch
New php-forum User
New php-forum User
 
Posts: 1
Joined: Mon Jul 14, 2014 4:33 am

Re: Parsing Data

Postby kladrian » Thu Aug 14, 2014 11:09 am

that looks like a json

so you have to decode it and use it like a normal object.

here's the code:
Code: Select all

try{
   $json = json_decode($jsondata);
   if (empty($json)){
      echo "invalid json";
      return;
   }
   // then you can access to variables
   $cmd = $json->cmd;
   echo $cmd;
   $last_heard = $json->coreInfo->last_heard;
   echo $last_heard;
   // to check if a property exists ...
   if (isset($json->result)) {
      $result = $json->result;
      echo $result;
   }
   // to check if a nested property exists u've to do write more code
   // @ char avoids php complains about non objects
   $prop = @$json->it->does->not->exists;
   if ($prop === NULL) {
      echo "it doesn't exists";
   }
}
catch (Exception $ee) {
   echo "failed to parse json file";
}




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

cron