Page 1 of 1

file_get_contents() alternative?

Posted: Mon Feb 09, 2009 9:38 pm
by Citizen
Here's my code:

Code: Select all

$url = "http://maps.google.com/maps/geo?q=$mapaddress&output=xml&key=$key";
$page = file_get_contents($url);
preg_match_all('#<coordinates>(.*?),(.*?),(.*?)</coordinates>#s', $page, $matches);
Basically, I use file_get_contents() to read the results sent back from google to get the latitude and longitude for a location.

Problem is, some of my clients do not have file_get_contents() enabled. Is there a php 4 + php 5 safe way to read the results without using a function that is going to be disabled by some of the bigger hosting companies?

Re: file_get_contents() alternative?

Posted: Mon Feb 09, 2009 9:50 pm
by t2birkey
There are actually many alternatives! There is cURL, fopen, include/require, etc.

I most commonly use cURL b/c there are so many options you can set. But once again, not everyone enables cURL. I will post my cURL function I often use to generally get data from a webserver. Many people use include/require isn't secure for including urls so i wont give any details for it, but fopen can be used to open files or urls.. first check that allow_url_fopen is enabled before using it or it will fail wanring you that the webserver doesn't support it.

Code: Select all

 
    function CURL($href,$posts = "") {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $href);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
        curl_setopt($ch, CURLOPT_HEADER, 1);
        if ($posts!=""){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
        }
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result=curl_exec($ch);
        curl_close($ch);
        return $result;
    }
 
You just say CURL("http://google.com").. if you want to send post data to the website just make a variable or use a string to say the data. Post data looks just like get data.. so it would be $page=CURL("http://google.com", "user=Citizen&tutorial=1"); I also love cURL because you can set any option you want.. I could say the useragent is internet explorer, netscape, a google crawl bot, etc.

Re: file_get_contents() alternative?

Posted: Mon Feb 09, 2009 10:02 pm
by Citizen
Thanks!