无法打开流:HTTP请求失败! HTTP / 1.0 400

时间:2015-10-28 05:28:01

标签: php xml yahoo-api

我有一个班级

class exchange_rates{

    var $currency = '"USDINR","TRYINR","SARINR","EURINR"'; 
    var $url ;
    var $handle;
    var $result;
    var $xml_index , $xml_val;

    public function __construct(){

            $this->url = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ('.$this->currency.')&env=store://datatables.org/alltableswithkeys';


    }

    public function fetch_Currency (){ 

            //echo $this->url ;
            $this->handle = file_get_contents($this->url);

            if ($this->handle) {
                    $this->result = fgets($this->handle, 4096);
                    $p = xml_parser_create();

                    xml_parse_into_struct($p, $this->result, $this->xml_val, $this->xml_index);

                    xml_parser_free($p);

                    fclose($this->handle);
        }
    }

    public function get_exchange(){
        echo "<pre>";
        var_dump($this->xml_val);
        echo "</pre>";
    }

}

我这样叫这个班级

$obj = new exchange_rates();
    $obj->fetch_Currency();
    $obj->get_exchange();

我得到的错误如下

Warning: file_get_contents(http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDINR","TRYINR","SARINR","EURINR")&env=store://datatables.org/alltableswithkeys): failed to open stream: HTTP request failed! HTTP/1.0 400 Unknown Version in C:\xampp\htdocs\ycc\currency_convertor.php on line 21
NULL

基本上我试图从URL获取XML。如果您解析以下网址

 http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDINR","TRYINR","SARINR","EURINR")&env=store://datatables.org/alltableswithkeys

您将看到XML结果,但通过我的代码,我无法下载

请帮帮我

谢谢

1 个答案:

答案 0 :(得分:4)

当我调试同样的事情时,我遇到了这个问题。对我来说,解决方案是你必须对URL的查询部分进行urlencode。

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

$data = file_get_contents($request);

希望这有助于某人!

更多信息:https://developer.yahoo.com/php/howto-reqRestPhp.html