使用来自url的file_get_contents获取内容/文件的问题或反向地理编码中的问题

时间:2011-08-05 09:30:57

标签: php xml-rpc reverse-geocoding php-5.2

我正在尝试使用php脚本中的google api进行反向地理编码(使用xmlrpc)。我在本地系统中编写了以下代码,但是当我在我们的网络服务器上尝试它失败时。

function reverseGeoCode()
{
    $url = "http://maps.google.com/maps/geo?json&ll=".$lat.",".$long;
    $data = file_get_contents(urlencode($url));
    if ($data == FALSE)
    {
        echo "failed";
    }
    else
    {
        echo "success";

        // parsing the json/xml ...
    }
}

我得到了o / p“失败”

我的本​​地php:php5.3.6和webser是5.2.9。 由于它不断失败我将网址更改为http://www.google.com以进行测试(不使用urlencode),然后在网络服务器中也失败了。如果任何人有想法解决我的错误请帮助。谢谢提前

4 个答案:

答案 0 :(得分:2)

网址看起来已经正确进行网址编码,因此请勿再次对其进行网址编码,这会导致网址在您的情况下无效。这就是你获得FALSE返回值的原因。有关返回值的含义,请参阅file_get_contentsDocs

而只是获取网址:

$data = file_get_contents($url);

如果这不起作用,则只对搜索参数进行urlencode:

$url = sprintf("http://maps.google.com/maps/geo?json&ll=%s,%s", 
                urlencode($lat), urlencode($long));

另请参阅url_encodeDocsUniform Resource Identifiers (RFC 2616 Section 3.2)以及Uniform Resource Identifiers (URI): Generic Syntax (RFC 2396)


如果您想了解更多请求失败的原因,您可以通过允许file_get_contents继续处理HTTP失败(请see this answer how to return the document on 4xx responses)来获取更多信息,如果您的网址有用,这可能很有用“正在使用已经是正确的了,您想了解服务器告诉您的更多信息。

除此之外,您可以check the response HTTP status code as well by getting the headers of the URL或使用$http_response_headerDocs

最后有Why doesn't file_get_contents work? wiki answer covering nearly everything that can go wrong and how to deal with it

答案 1 :(得分:1)

确保在php.ini

中设置了allow_url_fopen

答案 2 :(得分:1)

您应该通过查看PHP ini设置allow_url_fopen

的值来检查服务器上是否启用了“URL包装器”

编辑:你可以使用这段代码检查它是否已启用

echo php_ini_get('allow_url_fopen') ? 'Enabled' : 'Disabled';

答案 3 :(得分:0)

如果你做的一切都没事,但仍然没有成功!你正在使用Redhat或CentOs ..然后尝试这个命令

setsebool -P httpd_can_network_connect on

某些RedHat和CentOs安装会阻止httpd向外部服务器发送请求。