来自Google Finance API调用的JSON中的大幅削减

时间:2011-01-18 23:15:54

标签: php json google-finance

我一直在使用Google财经API成功收集一些股票信息。问题是,在调用http://www.google.com/finance/info?infotype=infoquoteall&q=[$tickerSymbol]之后,Google返回的JSON在其之前添加了//,因此无法使用PHP的json_encode()对字符串进行编码。 JSONLint JSON Validator确认//无效。显而易见的解决方法是从JSON的开头剥去斜杠。尽管如此,我还是想知道谷歌为什么要向它返回的JSON添加斜杠。额外的斜杠背后有什么目的吗?当其他语言忽略多余的字符时,这是PHP json_encode()的怪癖吗?我做错了吗?

以下是带有前导斜杠的http://www.google.com/finance/info?infotype=infoquoteall&q=AAPL请求结果示例。

// [ {
"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"
}
]

2 个答案:

答案 0 :(得分:5)

对于那些寻找现成答案的人来说,这是PHP的一个工作示例;清理JSON并将其转换为对象。可以轻松提取值。

第二个是让它更加精彩,当访问页面时,它会向PubNub频道发送推送消息(cron是你的朋友)。 PubNub消息可以通过javascript轻松接收,因此直播...

<?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
?>

当然,如果你需要一些实时更新,有更好的选择。我只想每30分钟/ 60分钟更新一次。

答案 1 :(得分:2)

我想这是因为Google不希望您使用该JSON,他们建议您使用Google Data API。