Parse page in to array in PHP - 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?

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.

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

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
// ...
}
?>

Related

input JSON data type in MySql column

I'm using Algolia as my site's search engine, Algolia wants '_geoloc' attribute to be a JSON object like this in order to enable searching based on locations :-
{
"rahn": "e369853df766fa44e1ed0ff613f563bd",
"_geoloc": { "lat" : 23.788117809722195 , "lng" : 86.41868225381391 }
},
But when I exported my Mysql database in JSON its '_geoloc' attribute is like this :-
{
"sadad": "32rf4rsdf43444rtte4e3rrt3342334",
"_geoloc": "{ \"lat\" : 23.788117809722195 , \"lng\" : 86.41868225381391 }"
},
Row Info
name :- _geoloc
type :- longtext
collation :- utf8mb4_bin
attributes :- none
Test the next code:
$a_bag = "UPDATE client_storage
SET _geoloc = JSON_OBJECT('lat', $client_lat, 'lng', $client_long)
WHERE client_id = 567";
and check the value saved into the column.
Well Since I didn't find any solution to my problem I have done this other alternative i.e. I used Python for doing these changes to my JSON and You can do it too to do any changes to any type of file.
Here's my python code to do this:-
import json
with open('Your_file_location.json', encoding='cp850') as json_file:
prd_json_file = json.load(json_file)
for prd in prd_json_file:
if(prd['_geoloc'] != ''):
prd['_geoloc'] = json.loads(prd['_geoloc'])
else:
prd['_geoloc'] = { "lat": 23.378536756304715, "lng": 85.33722513906919 }
with open('Your_file_location.json','w', encoding='cp850') as json_file:
json.dump(prd_json_file,json_file)
print('success')

Error executing phantom js on windows . Invalid json

I am using phantom library to convert my highcharts to PDF.
When I execute the code
$result = json_decode(trim(shell_exec($this->getBinPath() . ' ' . escapeshellarg(json_encode($args)))));
Error is returned saying
unable to parse json
Command being run is
"C:\www\myproject\vendor\kriansa\h2p\bin/win32/phantomjs.exe" "C:\www\myproject\vendor\kriansa\h2p\bin/converter.js" "{ destination : C:\\Windows\\TEMP\\14b6e6edc209b6e731bdbc79976a9430438409ae.tmp , request :{ uri : C:\\Windows\\TEMP\\127ef8f78c335d9af694a9cef0423541dd17a256.html , method : GET }, orientation : Portrait , format : A3 , zoomFactor :1, allowParseCustomFooter :false, allowParseCustomHeader :false, border : 1cm , header :null, footer :null}"
What should I check for ? I have validated the json being passed as argument.
Edit
I checked this also
"C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/win32/phantomjs.exe" "C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/converter.js" {"destination":"C:\\Windows\\TEMP\\d4ca24267110d5c234b7a006f1ae5c03da248e88.tmp","request":{"uri":"C:\\Windows\\TEMP\\9b5d4d28689c3bc00afc0831666d6ee39a934b5c.html","method":"GET"},"orientation":"Portrait","format":"A3","zoomFactor":1,"allowParseCustomFooter":false,"allowParseCustomHeader":false,"border":"1cm","header":null,"footer":null}
same error again
I'm using this tool to validate JSON for JS, it has to pass the JS eval tests.
This JSON parses correctly:
{
"destination" : "C:\\Windows\\TEMP\\14b6e6edc209b6e731bdbc79976a9430438409ae.tmp",
"request":
{
"uri" : "C:\\Windows\\TEMP\\127ef8f78c335d9af694a9cef0423541dd17a256.html",
"method" : "GET"
},
"orientation" : "Portrait",
"format" : "A3",
"zoomFactor" :1,
"allowParseCustomFooter" :false,
"allowParseCustomHeader" :false,
"border" : "1cm",
"header" :null,
"footer" :null
}
Notice the quotes around they keys (destination, etc) and quotes around non-native types and strings. You can leave null, boolean, integers, decimals without quotes.
Edit
I think you also need to wrap the JSON in quotes in the command call
"C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/win32/phantomjs.exe"
"C:\www\cimba_aboutmy360\vendor\kriansa\h2p\bin/converter.js"
"{'destination':'C:\\Windows\\TEMP\\d4ca24267110d5c234b7a006f1ae5c03da248e88.tmp','request':{'uri':'C:\\Windows\\TEMP\\9b5d4d28689c3bc00afc0831666d6ee39a934b5c.html','method':'GET'},'orientation':'Portrait','format':'A3','zoomFactor':1,'allowParseCustomFooter':false,'allowParseCustomHeader':false,'border':'1cm','header':null,'footer':null}"

How to parse datetime for use in highchart graph?

Here i got timestamp value
$user_array1[] = $val['timestamp'];
$graph_data1 ='';
if(is_array($user_array1))
{
$graph_data1 = implode(',',$user_array1);
}
Output when i print_r($graph_data1);
I got
,2014-05-26 00:43:45,2014-05-26 00:43:52,2014-05-26 00:43:592014-05-26
00:43:19,2014-05-26 00:43:24,2014-05-26 00:43:27,2014-05-26
00:43:30,2014-05-26 00:43:34,2014-05-26 00:43:37,2014-05-26
00:43:41,2014-05-26 00:43:45,2014-05-26 00:43:52,2014-05-26
00:43:59,2014-05-26 00:44:11
Highchart side :
categories: [<?php echo $graph_data1 ?> ]
it does not show any things.
In your current format of data, your string are considered malformed, and therefore incorrect for input in highcharts. You must format it correctly fist. Consider this example:
$graph_data1 = "'".implode("','", $user_array1)."'";
Should output something like this:
'2014-05-26 00:43:45','2014-05-26 00:43:45','2014-05-26 00:43:45' ... etc ...

jquery Autocomplete working with older versions of the browsers but not new ones?

here is the JSON data for my auto complete
{ "list" : [ {
"genericIndicatorId" : 100,
"isActive" : false,
"maxValue" : null,
"minValue" : null,
"modificationDate" : 1283904000000,
"monotone" : 1,
"name":"Abbau",
"old_name" : "abbau_change_delete_imac",
"position" : 2,
"systemGraphics" : "000000",
"unitId" : 1,
"valueType" : 1,
"description" : "Abbau",
"weight" : 1
}]}
and the code which i wrote is
$("#<portlet:namespace />giName").autocomplete({
source :`enter code here` function( request, response ) {
$.post(
"<%=AJAXgetGIs%>",
{
"<%=Constants.INDICATOR_NAME%>" : request.term,
"<%=Constants.SERVICE_ID%>" : <%=serviceId%>
},
function( data ) {
response( $.map( data.list, function( item ) {
//alert(item.name + " || " + item.genericIndicatorId);
item.value = item.name;
return item;
}));
},
"json"
);
},
minLength : 2
i am using jquery-ui-1.8.14.autocomplete.min.js plugin for auto complete
the problem i am getting is it is not showing all the matched results in new browsers.
for example if i type "an" in which should matches to the "anzahl" keyword, the fire bug is showing error like "bad control character literal in a string". results are showing for the letters "as,sa....". any help would be appriciated
thank you
The error message means you have control characters in your JSON response (something like \n, \t, etc). Newlines and the other control characters are not allowed in JSON strings, according to ECMA262 5ed. You can fix it rather easily by escaping or removing those characters, either from PHP or from Javascript.
Here you can find an example of how you can fix it from PHP, as the problem most likely comes from json_encode (which I assume you're using): http://codepad.org/Qu7uPt0E
As you can see, json_encode doesn't escape the \n so you have to do it manually before outputting.
Now for the mistery related to older browsers. If you look at jQuery's parseJSON function you'll notice that it first tries to parse the string with the browser's builtin JSON object and if it doesn't find any, it will just do a (sort of) eval (which will work even with newlines). So it probably works for you on Firefox < 3.5 or IE < 8 which don't have a native JSON object.
Also, it probably works with other search terms (like as, etc) simply because they don't include a result which has control characters.
Adding to draevors correct answer.
Look at downloading the JSON2 library
https://github.com/douglascrockford/JSON-js
That is how i got around this problem

Leading slashes in JSON from Google Finance API call

I've been using the Google Finance API to successfully gather some stock info. The problem is that after a call to http://www.google.com/finance/info?infotype=infoquoteall&q=[$tickerSymbol], the JSON that Google returns has // added before it and therefore the string cannot be encoded using PHP's json_encode(). The JSONLint JSON Validator confirms that the //s are not valid. The obvious workaround is to strip the slashes from the beginning of the JSON. None-the-less, I am left wondering why Google is adding slashes to the JSON it is returning. Is there a purpose behind the extra slashes? Is this a quirk with PHP's json_encode() when other languages would simply ignore the extra characters? Am I doing something incorrectly?
Here is an example of the result of a request for http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL with the leading slashes.
// [ {
"id": "22144"
,"t" : "AAPL"
,"e" : "NASDAQ"
,"l" : "340.65"
,"l_cur" : "340.65"
,"ltt":"4:00PM EST"
,"lt" : "Jan 18, 4:00PM EST"
,"c" : "-7.83"
,"cp" : "-2.25"
,"ccol" : "chr"
,"el": "345.20"
,"el_cur": "345.20"
,"elt" : "Jan 18, 5:45PM EST"
,"ec" : "+4.55"
,"ecp" : "1.34"
,"eccol" : "chg"
,"div" : ""
,"yld" : ""
,"eo" : ""
,"delay": ""
,"op" : "327.05"
,"hi" : "344.76"
,"lo" : "326.00"
,"vo" : "66.34M"
,"avvo" : "11.28M"
,"hi52" : "348.48"
,"lo52" : "190.25"
,"mc" : "313.75B"
,"pe" : "22.49"
,"fwpe" : ""
,"beta" : "1.38"
,"eps" : "15.15"
,"name" : "Apple Inc."
,"type" : "Company"
}
]
For those looking for a ready answer, here is a working example with PHP; The JSON is cleaned and transformed into an object. Values can easily be extracted.
The second is just to make it more awesome, it sends a push message you a PubNub channel when page is accessed (cron is your friend). PubNub message can easily be received via javascript hence live...
<?php
//Obtain Quote Info
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXDB:DAX');
//Remove CR's from ouput - make it one line
$json = str_replace("\n", "", $quote);
//Remove //, [ and ] to build qualified string
$data = substr($json, 4, strlen($json) -5);
//decode JSON data
$json_output = json_decode(utf8_decode($data));
// get the last price
$last = $json_output->l;
//Output Stock price .
echo 'DAX: ' . $last;
//////////////////////////////
// send it through pubnub //
//////////////////////////////
require_once('Pubnub.php');
// Publish and Subscribe Keys
$publish_key = 'demo';
$subscribe_key = 'demo';
$subscribe_key = false;
// Create Pubnub Object
$pubnub = new Pubnub( $publish_key, $subscribe_key, $secret_key );
// Publish !
$channel = 'quoteTheDax';
$timestamp = $pubnub->time();
$pubish_success = $pubnub->publish(array(
'channel' => $channel,
'message' => array("last" => $last2, "ts" => $timestamp)
));
//Boom its send to ppl subscribed to this channel arround the world
?>
of course if you need something live updating all the time there are better options. I was just looking to update every 30min/60min.
I guess it's because google don't want you to work with that JSON, they recommend to use the Google Data API.

Categories