Jump to content

Parsing Data


olliemitch

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
https://forums.phpfreaks.com/topic/289863-parsing-data/
Share on other sites

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
https://forums.phpfreaks.com/topic/289863-parsing-data/#findComment-1485004
Share on other sites

Archived

This topic is now archived and is closed to further replies.

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