使用php在curl中获取Empty变量

时间:2012-09-05 11:11:26

标签: php curl yahoo-api yahoo-finance

我正在尝试使用Curl执行一个url,我得到空输出。

但是,如果我们在浏览器中复制粘贴相同的网址,我们就会获得价值

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22YHOO%22,%22AAPL%22,%22GOOG%22,%22MSFT%22%29&env=http://datatables.org/alltables.env&format=json

然而,当我尝试使用Curl在php中获取值时,我得到Null

php code

 <?php

$BASE_URL = "http://query.yahooapis.com/v1/public/yql"; 



    // Form YQL query and build URI to YQL Web service
    $yql_query = 'select * from yahoo.finance.quotes where symbol in ("YHOO","AAPL","GOOG","MSFT")&env=http://datatables.org/alltables.env';
    $yql_query_url = $BASE_URL . "?q=" .$yql_query. "&format=json";


    // Make call with cURL
    $session = curl_init($yql_query_url);
    curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
    $json = curl_exec($session);


    echo "<pre>";
    print_r($json);exit;

?>

任何建议??????

3 个答案:

答案 0 :(得分:2)

您需要使用json_decode

检查手册 -

http://php.net/manual/en/function.json-decode.php

现在检查这个工作代码 - (至少我的工作) -

<?php

$yql_query_url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22YHOO%22,%22AAPL%22,%22GOOG%22,%22MSFT%22%29&env=http://datatables.org/alltables.env&format=json"; 

    // Make call with cURL
    $session = curl_init($yql_query_url);
    curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
    $json = curl_exec($session);

$jsonnew=json_decode($json,true);

    echo "<pre>";
    print_r($jsonnew);

?>

答案 1 :(得分:1)

以下代码对我有用

<?php

$BASE_URL = "http://query.yahooapis.com/v1/public/yql"; 
    $query = 'select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28"YHOO","AAPL","GOOG","MSFT"%29&env=http://datatables.org/alltables.env&format=json';
    echo $yql_query_url = $BASE_URL . "?q=" .$query;


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$yql_query_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec ($ch);
    curl_close ($ch);
    print_r($content);
?>

查询必须正确编码。

检查

答案 2 :(得分:0)

我收到了错误。

在使用CURL

之前,我必须使用“urlencode”函数对Url进行编码

而不是

$yql_query_url = $BASE_URL . "?q=" .$yql_query. "&format=json";

我必须使用

$yql_query_url = $BASE_URL . "?q=" .urlencode($yql_query). "&format=json";

并且它有效:) lol