Error executing phantom js on windows . Invalid json - php

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}"

Related

PHP json_encode - Same Code once delivers an Array and once an object

I am using the same code within two PHP- classes. I copied and pasted it.
In one class an Array is delivered to the JavaScript in which I use a copied/pasted piece of code, too and once an Object.
Here is the PHP- Code:
private $status_good = array('Status' => 'good');
private $status_fail = array('Status' => 'fail');
echo json_encode($this->status_fail);
And here is the JS/jquery- Code:
$.post("./someclass.php",
{
code : this.code,
input : this.input
},
function( data ){
console.log("Data: ")
console.log(data );
}
Once the console says: Data: {"Status":"fail"}
In the other script: Data: Object { Status: "fail" }
I am doing no UTF- manipulation nor any header- manipulation.
Please be so kind and tell me how this may happen with exactly the same code in different classes.
Thanks in advance.
Add the dataType argument to $.post and/or set Content-type header in the php.
$.ajax does a "best guess" at the data type being returned if it is not explicitly told what to expect and there is no header to help it decide.
It would appear that it is getting it right in the one case and parsing JSON and in the other it is treating it as text and returning a string to the callback.
$.post("./someclass.php",
{
code : this.code,
input : this.input
},
function( data ){
console.log("Data: ")
console.log(data );
},'json')

how to convert this json data in php

I am using an api which is giving me a very strange json format.. i'm posting its data which i am getting thru it..
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "f53762dab34022e9d851ab71e0bf166f" };
I'm trying to print this data in php but i'm not able to do that..nothing is showing on my webpage,....
My code are..
First i tried,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
echo $info;
?>
My second attempt was,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info->h;
?>
My last attempt was,
<?php
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info=file_get_contents($url);
$info=json_decode($info,true);
$info['h'];
?>
Nothing is happening..
please somebody help me
API Url converted...
The page is sending
"info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "058ce93db26fce4a9f1cb41ae2e7c1bb" };"
You cannot use json_decode on this because the info = and the ; at the end are not json. You have to strip the info = and the ;.
$url="http://www.website-name.com/a/itemInfo/?video_id=IN7o2Iy89WQ&ac=www";
$info = file_get_contents($url);
$info = trim($info, "info = ");
$info = rtrim($info, ";");
$json = json_decode($info, true);
echo $json['status'];
The data I got from the URL in your example is
info = { "title" : "Asian Dad: B Again!? (you die)", "image" : "http://i.ytimg.com/vi/IN7o2Iy89WQ/default.jpg", "length" : "2", "status" : "serving", "progress_speed" : "", "progress" : "", "ads" : "", "pf" : "", "h" : "5cddd4d1667f24aa9a0f5a6cc21e24e3" };
That's an executable JavaScript snippet, not actually JSON. The reason your php is failing is due to the 'info =' part... json_encode returns null on decoding failure.
While this is an assignment of a variable to a JavaScript object, that would work as JSON too if you removed the 'info =' and semicolon. Assuming the responses are predictable, you could do this with php str_replace, but finding an API that returns JSON for your source would be a more reliable and clean solution.
If you're getting NULL when you var_dump($info) on the second line as you mentioned in comments, then file_get_contents() doesn't retrieve the data.
It's most likely because allow_url_fopen is set to false in PHP.ini
From the json_decode() documentation:
Takes a JSON encoded string and converts it into a PHP variable.
If 2nd parameter is set to true it returns an array !
SO your first and second attempt is wrong.! It should work third attempt. Just check if you retrieve the data.

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

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