php - 来自 Google Finance API 调用的 JSON 中的前导斜线

标签 php json google-finance

我一直在使用 Google Finance 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"
}
]

最佳答案

对于那些正在寻找现成答案的人,这里有一个 PHP 的工作示例; JSON 被清理并转换为对象。可以很容易地提取值。

第二个只是为了让它更棒,当页面被访问时,它会向你发送一条推送消息到 PubNub channel (cron 是你的 friend )。 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 分钟更新一次。

关于php - 来自 Google Finance API 调用的 JSON 中的前导斜线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4730163/

相关文章:

php - date_add() 在 PHP 中更改 2 个变量而不是 1 个

php - 如何调整颜色背景的大小

javascript - 使用 Angular 更改存储在 JSON 中的 bool 值?

Play 2.1.1中Json写入

java - 使用 Jackson 是否可以忽略所有循环关系而无需添加注释?

google-apps-script - 谷歌金融作为 ArrayFormula 的论据

php - XAMPP MySQL 关闭

php - 在 MySql 数据库中添加新记录时使用 Jquery 自动更新 Div

google-sheets - 如何从谷歌财经获取特定日期的股票价格?

python - 固定 yield 数据在线