PHP: Fetching data from remote site

Use cURL() functions:

$c = curl_init();
curl_setopt_array($c, $opts); 
$data = curl_exec($c);  
$info = curl_getinfo($c);
$error = curl_error($c);
curl_close($c);
  • line 2: see next section on $opt
  • line 3: data will be returned if CURLOPT_RETURNTRANSFER set to true
  • line 4: header info, including http status, size etc in array format

Setting options

Typically the param $opt for curl_setopt_array() (php V5+). for more options, read this.

$opts = array(
    CURLOPT_URL => $url,
    CURLOPT_HTTPGET => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'],
);

cUrl info

Example of data returned from curl_getinfo():

Array
(
    [url] => http://....
    [content_type] => application/xml
    [http_code] => 302
    [header_size] => 212
    [request_size] => 197
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.373705
    [namelookup_time] => 0.054075
    [connect_time] => 0.212869
    [pretransfer_time] => 0.212979
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => 0
    [upload_content_length] => 0
    [starttransfer_time] => 0.373589
    [redirect_time] => 0
}

Leave a Reply

Your email address will not be published. Required fields are marked *