开发者

Problem in getting contents/ files using file_get_contents from url or Problem in reverse geo coding

开发者 https://www.devze.com 2023-03-26 06:52 出处:网络
I am trying reverse geocode using google api in php script(using xmlrpc).I wrote the following code in my local system its works fine,but when I try in our webserver it fails.

I am trying reverse geocode using google api in php script(using xmlrpc).I wrote the following code in my local system its works fine,but when I try in our webserver it fails.

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 ...
    }
}

I got the o/p "failed"

my local php: php5.3.6 and webser is 5.2.9. Since it continously failed i change the url to http://www.google.com for testing(with out using urlencode),then also it failed in webserver.If开发者_开发知识库 any one have idea to retify my error Please help.Thanks in advance


The URL looks already properly URL-encoded, so don't URL-encode it again which results in an URL that does not work in your case. That's why you get the FALSE return value. For the meaning of the return values please see file_get_contentsDocs.

Instead just get the URL:

$data = file_get_contents($url);

If that does not work, only urlencode the query arguments:

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

See as well url_encodeDocs and Uniform Resource Identifiers (RFC 2616 Section 3.2) as well as Uniform Resource Identifiers (URI): Generic Syntax (RFC 2396).


If you would like to find out more why the request failed, you can gain more information by allowing file_get_contents to proceed on HTTP failures (Please see this answer how to return the document on 4xx responses), that can be useful if the URL you're using is already correct and you would like to know more about what the server is telling you.

Next to that you can check the response HTTP status code as well by getting the headers of the URL or by using $http_response_headerDocs

And finally there is the Why doesn't file_get_contents work? wiki answer covering nearly everything that can go wrong and how to deal with it.


Make sure you have allow_url_fopen set to on in your php.ini


You should check that "URL wrappers" are enabled on the server by looking at the value of the PHP ini setting allow_url_fopen

Edit: you can check whether it's enabled or not with this piece of code

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


If you did everything right and still did not succeed! And you are using Redhat or CentOs.. Then try this command

setsebool -P httpd_can_network_connect on

Some RedHat and CentOs installations block httpd from sending requests to external servers.

0

精彩评论

暂无评论...
验证码 换一张
取 消