Kamis, 13 Januari 2011

Using cURL to Read the Contents of a Web Page

Below is the code we will be using:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
$result = curl_exec($ch);
curl_close($ch);

Broken down we have:

    * $ch = curl_init(); intiate the curl object
    * curl_setopt($ch, CURLOPT_URL, $file); specify the file or url to load
    * curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); tell it to return the raw content
    * curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']); Simulate the http referer
    * $result = curl_exec($ch); perform the cURL request
    * curl_close($ch); close the connection

<?php
function bm_getWeather ($code = '', $temp = 'c') {
 $file = 'http://weather.yahooapis.com/forecastrss?p=' . $code . '&u=' . $temp;

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $file);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
 $result = curl_exec($ch);
 curl_close($ch);

 $output = array (
  'temperature' => bm_getWeatherProperties('temp', $result),
  'weather' => bm_getWeatherProperties('text', $result),
  'weather_code' => bm_getWeatherProperties('code', $result),
  'class' => 'weatherIcon-' . bm_getWeatherProperties('code', $result),
 );

 return $output;
}

function bm_getWeatherProperties ($needle, $data) {
 $regex = '<yweather :condition.*' . $needle . '="(.*?)".*/>';
 preg_match($regex, $data, $matches);
 return $matches[1];

 }

Tidak ada komentar:

Posting Komentar