Leading slashes in JSON from Google Finance API call - php

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.

Related

Get JSON from a URL by PHP

I have a URL that returns a JSON object like this:
{
"USD" : {"15m" : 7809.0, "last" : 7809.0, "buy" : 7809.85, "sell" : 7808.15, "symbol" : "$"},
"AUD" : {"15m" : 10321.42, "last" : 10321.42, "buy" : 10322.54, "sell" : 10320.3, "symbol" : "$"},
}
URL : https://blockchain.info/ticker
more info : https://blockchain.info/api/exchange_rates_api
I want to get all the data from the first line and echo it and to have it keep requesting it so its live
I have used the examples on git hub
https://github.com/blockchain/api-v1-client-php/blob/master/docs/rates.md
but it displays all of the data output and you have to refresh it to get it updated
please can some one point me in the right direction
ideally I would end up with something like
15 m Last Buy Sell
USD ($) 7794.87 7794.87 7795.72 7794.02
I have the table and data going to the table but its echoing the whole data set rather than the first line and also I dont know how to select individual fields
How can I do it through PHP?
What you need is a request php page, which will make:
1 - Get data from te site:
$data = file_get_contents('https://blockchain.info/ticker');
2 - decode the json
$decodedData = json_decode($data);
3 - Here you can access it using OOP:
var_dump($decodedData->USD);
The point here will be to retrieve data as you wish, you can mix it up with HTML in a table for example.
Then, you need a JS script, that will execute a function with setInterval, each few miliseconds. That function should make a request to a PHP page that you created earlier, get that data and change with the updated one.
This Should do it:
<?
$seconds = 5;
function get_live_quote($key){
$json_string = file_get_contents('https://blockchain.info/ticker');
$json_array = json_decode($json_string, TRUE);
$quote = $json_array[$key];
$keys = implode(" ",array_keys($quote));
$values = implode(" ", array_values ($quote));
return "$keys $values \n";
}
while(TRUE){
echo get_live_quote("USD");
sleep($seconds);
}
Save the preceding code to a file like "quote.php". Then from your terminal just run: php quote.php

making JSON string manually in php which is breaking line on urls

I am trying to create json manually using string in php by parsing an xml file. I created the whole json but when i am validating it; i can see unnecessary line breaks in between which causes the validation to fail.
This is part of my json.
"basicInfo": {
"title": "Mini Figures Heroes Assemble Building Toys Taskmaster Martain Storm Thor #v6lo01",
"viewItemURL": "http
://www.ebay.com/itm/Mini-Figures-Heroes-Assemble-Building-Toys-Taskmaster-Martain-Storm-Thor-v6lo01-
/351370851384?pt=LH_DefaultDomain_0",
"galleryURL": "http://thumbs1.ebaystatic.com/m/myYu_MI3-mPtA6s3bJboaVA
/140.jpg",
"pictureURLSuperSize": "http://i.ebayimg.com/00/s/OTAwWDEzNTI=/z/lQEAAOSwqu9VJ-Fy/$_3.JPG",
"convertedCurrentPrice": "7.76",
"shippingServiceCost": "0.0",
"conditionDisplayName": "New",
"listingType": "Auction",
"location": "China",
"categoryName": "Comic Book Heroes",
"topRatedLising": "false"
},
As you can see that the line is breaking for url.
In the php code i am just concatenating directly.
$resultxml.='"viewItemURL":"'.$grandchild->viewItemURL;
$resultxml.='",';
$resultxml.='"galleryURL":"'.$grandchild->galleryURL.'",';
I have no idea what am i doing wrong.
Use json_encode. An example:
<?php
/*
If $grandchild->viewItemURL = "http
://www.ebay.com/itm/Mini-Figures-Heroes-Assemble-Building-Toys-Taskmaster-Martain-Storm-Thor-v6lo01-/351370851384?pt=LH_DefaultDomain_0"
Value whith carriage return
*/
$data = array(
"basicInfo" => array(
"title" => $grandchild->title,
"viewItemURL" => str_replace( "\n", '', $grandchild->viewItemURL ),
"galleryURL" => str_replace( "\n", '', $grandchild->galleryURL ),
"pictureURLSuperSize" => str_replace( "\n", '', $grandchild->pictureURLSuperSize ),
"convertedCurrentPrice" => $grandchild->convertedCurrentPrice,
// .
// . and more items
// .
)
);
$dataJson = json_encode( $data );
?>
I agree with the comments, that you shouldn't create it manually.
However, to answer your question...
I copied your JSON and looked at it, and all the URLs have a space between : and // in the http://.
"viewItemURL": "http: //www.ebay.com/itm/Mini[...]",
"galleryURL": "http: //thumbs1.ebaystatic.com[...]",
As you can see, you also have a space after each colon ":", i.e. between the colon and the JSON value.
I guess you have another function (not posted here), which adds the space after each colon and it does that for URL as well.

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

Receive array of numbers in php (JSON)

I would like to get an array from my JSON in php.
This way I get the JSON string from URL in my android application:
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);
To receive [phone=123] in php I use this:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
That is working for one phonenumber, but now I need more than one phonenumber.
The data in Logcat (reported with "Log.d("to php: ", paramstodb.toString())" ) is displayed as:
to php:﹕ [phone=[0127361744, 0132782422, 0137173813, 0142534646, 0123617637435, 013391339494, 01383375633, 013878942423, 013891748422, 01389487285, 014434354234, 01848481371, 018831789414, 021238133441231, 021371689411, 02183718454, 123, 456]]
How can I get all numbers in an array in php?
This is not working so far:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
$phpArray = json_decode($phone, true);
I hope you can help me again ;-)
If the JSON input to the PHP script really is this JSON
{ "phone": [ "123", "456", "789"] }
then PHP's json_decode should handle it without problems.
You can try this code to see it's actually working and use it to detect where something goes wrong:
// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';
// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString . PHP_EOL;
// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);
// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;
// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));
This should print:
Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
'phone' =>
array(3) {
[0] =>
string(3) "123"
[1] =>
string(3) "456"
[2] =>
string(3) "789"
}
}
which shows the JSON decodes to a proper PHP array. An array of strings, to be precise, and not numbers as requested. Turning the strings into numbers in PHP will be easy to do, but maybe you could also make sure on the call site that you send numbers and not strings.
If your original code does not work, I guess the incoming data is either no properly encoded JSON or there is some magic escaping going on (magic quotes hell, should be turned off in today's PHP, but could be a reason for garbled script input).
To make sure your JSON data is not truncated and to also save you from potential URL-encoding issues, I also suggest sending the JSON via HTTP POST, not HTTP GET.

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.

Categories