Curl不工作,错误:could 't connect to host


Curl not working, error: couldn't connect to host

我使用curl从特定站点api.wunderground.com获取天气信息,问题是它不起作用。我也尝试过使用file_get_contents函数,但它也不起作用。下面是我的curl代码:

function get_web_page($url)
        {
            //echo "curl:url<pre>".$url."</pre><BR>";
        $options = array(
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_USERAGENT      => "spider", // who am i
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 15,      // timeout on connect
            CURLOPT_TIMEOUT        => 15,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
            CURLOPT_PROXY          => null,
        );                  
        $ch         = curl_init($url);
        curl_setopt_array( $ch, $options );
        $content    = curl_exec( $ch );
        $err        = curl_errno( $ch );
        $errmsg     = curl_error( $ch );
        $header     = curl_getinfo( $ch,CURLINFO_EFFECTIVE_URL );
        curl_close( $ch );
        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        //change errmsg here to errno
        if ($errmsg)
        {
            echo "CURL:".$errmsg."<BR>";
        }
        return $content;
        }
        $url        =   "http://api.wunderground.com/api/67927f145c532a19/geolookup/conditions/q/uae/dubai.json";
        get_web_page($url);

我已经检查了我的服务器设置,启用了curl并且服务器正在使用端口80。有谁能帮我一下吗?我想不出主意了。

你只需要回显输出。

echo get_web_page($url);
编辑:

也可以使用file_get_contents

<?php
$url="http://api.wunderground.com/api/67927f145c532a19/geolookup/conditions/q/uae/dubai.json";
echo file_get_contents($url);
?>

代码更新:

<?php
function get_web_page($url)
{    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $curl_result = curl_exec($ch);
    curl_close ($ch);
    return $curl_result;
}
$url="http://api.wunderground.com/api/67927f145c532a19/geolookup/conditions/q/uae/dubai.json";
echo get_web_page($url);
?>

我尝试了相同的代码,得到了

的响应

{"响应":{"版本":"0.1"termsofService":"http://www.wunderground.com/weather/api/d/terms.html"功能":{"geolookup":1,"条件":1}

以上代码是正确的。您只是忘记打印函数

返回的值

API似乎可以阻止可疑的用户代理。尝试使用标准的浏览器用户代理而不是spider

使用normal(浏览器的用户代理),API返回正常响应

也许你通过代理连接到互联网。您可以通过在curl_setopt函数中设置代理来获得它。

直接添加

        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_PROXY => false,

它解决了这个问题