PHP Yahoo没有返回数据

时间:2015-12-21 21:11:34

标签: php yahoo-finance

我尝试使用localhost / quote.php进行以下操作?symbol = IBM但是$ 42数据在第42行显示为空,表示缺少数据。

<?php



 // require ?symbol=...

 if (empty($_GET["symbol"]))

 {

 trigger_error("Missing symbol", E_USER_ERROR);

 }




 echo $_GET["symbol"];

 $_GET["symbol"] = "IBM";


 // headers for proxy servers

 $headers = [

 "Accept" => "*/*",

 "Connection" => "Keep-Alive",

 "User-Agent" => sprintf("curl/%s", curl_version()["version"])

 ];



 // open connection to Yahoo

 $context = stream_context_create([

 "http" => [

 "header" => implode(array_map(function($value, $key) {return sprintf("%s:  %s\r\n", $key, $value); }, $headers,

 array_keys($headers))),

 "method" => "GET"

 ]

 ]);

 $handle =    fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s=  {$_GET["symbol"]}", "r", false, $context);

 if ($handle === false)

 {

 trigger_error("Could not connect to Yahoo!", E_USER_ERROR);

 }





 // download first line of CSV file

 $data = fgetcsv($handle);
 print_r($data);

 if ($data === false || count($data) == 1)

 {

 trigger_error("Missing data", E_USER_ERROR);

 }



 // close connection to Yahoo

 fclose($handle);



 // ensure symbol was found

 if ($data[2] === "0.00")

 {

 trigger_error("Missing price", E_USER_ERROR);

 }



 // prepare stock as an associative array

 $stock = [

 "symbol" => $data[0],

 "name" => $data[1],

 "price" => floatval($data[2])] ;

 // output stock as JSON

 header

("Content-Type: application/json");

 print(json_encode($stock));



 ?>

1 个答案:

答案 0 :(得分:3)

您的网址包含空格:

fopen("http://download.finance.yahoo.com/d/quotes.csv?f=snl1&s=  {$_GET["symbol"]}",
                                                               ^^

您需要trim()

error reporting添加到文件的顶部,这有助于查找错误。

<?php 
error_reporting(E_ALL); // you could also use '-1' to get all errors.
ini_set('display_errors', 1);

// rest of your code

旁注:只应在暂存时进行显示错误,而不是生产。

  • var_dump()&#39;}是您可以在开发过程中使用的另一种工具