olliemitch Posted July 14, 2014 Share Posted July 14, 2014 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 More sharing options...
Ch0cu3r Posted July 14, 2014 Share Posted July 14, 2014 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 More sharing options...
olliemitch Posted July 15, 2014 Author Share Posted July 15, 2014 Thank you. This was a massive help. I knew there had to be an easy way to extract from something that looked so structured. Link to comment https://forums.phpfreaks.com/topic/289863-parsing-data/#findComment-1485169 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.