user2443639
user2443639

Reputation: 55

Parse page in to array in PHP

I am retrieving events from a CCTV system which is returning data in the following format,

[ 
{ alarmimage : '060429.0', timestamp : '1370099686.721', date : '2013-06-01', time : '16:14:46', events : 'VM' }, 
{ alarmimage : '060428.0', timestamp : '1370097952.081', date : '2013-06-01', time : '15:45:52', events : 'VM' }, 
{ alarmimage : '060427.0', timestamp : '1370097946.972', date : '2013-06-01', time : '15:45:46', events : 'VM' }, 
{ alarmimage : '060426.0', timestamp : '1370084199.546', date : '2013-06-01', time : '11:56:39', events : 'VM' }, 
{ alarmimage : '060425.0', timestamp : '1370083407.462', date : '2013-06-01', time : '11:43:27', events : 'VM' } 
] 

I am simply using get_data() to return the above, what is the most effective way to loop through each of these values to display as a list of events/ images?

Upvotes: 0

Views: 101

Answers (3)

Hauke P.
Hauke P.

Reputation: 2833

Since the key names you'll get from your CCTV system are not in quotes, the string is not a valid JSON string. You won't be able to parse it with json_decode without performing some ugly string modification.

When searching for an alternative, I found this answer: https://stackoverflow.com/a/6250894/1560865

The answer recommends to use the fact that JSON is a subset of YAML. Since YAML is a bit less strict about the quotes, you'll therefore should be able to parse your string with a YAML parser.

Upvotes: 1

Hauke P.
Hauke P.

Reputation: 2833

Use json_decode() with something like this:

<?php

$encdata = getTheData(); // your method to get the string
$data = json_decode($encdata);
foreach($data => $row)
{ 
    // access the row members like this:
    // $row->alarmimage
    // $row->timestamp 
    // $row->date
    // ...
 }

 ?>

Upvotes: 0

bpoiss
bpoiss

Reputation: 14003

Thats a format called json (javascript object notation).

You can parse it very simple with json_decode(), see: http://php.net/manual/en/function.json-encode.php

Upvotes: 1

Related Questions