PHP Parse Yahoo Finance获得505 HTTP错误

时间:2014-03-20 06:44:37

标签: php curl

<?php

$feedURL = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("EURUSD","GBPUSD")&env=store://datatables.org/alltableswithkeys';

$feedDATA = file_get_contents(urlencode($feedURL));

print_r($feedDATA);


?>

我试图解析yahoo finance for Forex Price feed但我收到此错误

HTTP/1.0 505 HTTP Version Not Supported in /home/site1/public_html/forex/getprice.php on line 12

如何解决此问题并在XML中解析xml 1.6551以获取EUR / USD和GBP / USD

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

您不应该对整个网址进行编码,只需要对参数进行网址编码。

PHP有一个很棒的 http_build_query 函数可以帮助你构建查询字符串。

代码:

$feedURL = 'http://query.yahooapis.com/v1/public/yql';
$params = array(
  'q' => 'select * from yahoo.finance.xchange where pair in ("EURUSD","GBPUSD")',
  'env' => 'store://datatables.org/alltableswithkeys'
);

$feedDATA = file_get_contents($feedURL.'?'.http_build_query($params));

print_r($feedDATA);

如何解析xml数据?

您甚至可以将网址传递给SimpleXMLElement的构造函数。

$xml = new SimpleXMLElement($feedURL.'?'.http_build_query($params), null, true);

foreach ($xml->results->rate as $rate) {
  echo $rate->Name . PHP_EOL;
  echo $rate->Rate . PHP_EOL;
}

答案 1 :(得分:0)

你做错了urlencode($feedURL)。我的意思是你正在编码整个网址!!

$feedDATA = file_get_contents($feedURL);

您需要对GET参数的查询部分进行编码。方法如下:

$feedURL = 'http://query.yahooapis.com/v1/public/yql?q='.urlencode('select * from yahoo.finance.xchange where pair in ("EURUSD","GBPUSD")').'&env=store://datatables.org/alltableswithkeys';