Jump to content

Parsing Data


olliemitch
Go to solution Solved by Ch0cu3r,

Recommended Posts

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.

Link to comment
Share on other sites

  • Solution

No need for regex.

 

What you have retrieved is a data object encoded in JSON.

 

PHP has a function called json_decode which will transform the json data back into a object. Example usage

$json_string = file_get_contents(...);

$data = json_decode($json_string);

// output the cmd property
echo 'CMD: '.$data->cmd.'<br />';

// output the name property
echo 'NAME: '.$data->name.'<br />';

// output last_heard value from the coreInfo property
echo 'LAST HEARD: '.$data->coreInfo->last_heard;
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.