function _yr_verdata_xml in Yr Weatherdata 6
Function for retrieving XML data from yr.no
Parameters
$url: The string to append to "http://yr.no/".
Return value
An object made with simplexml based on the XML data from yr.no.
2 calls to _yr_verdata_xml()
- theme_yr_verdata_location_block in ./
yr_verdata.module - theme_yr_verdata_location_page in ./
yr_verdata.module - Theming of a page with detailed forecast for a location.
File
- ./
yr_verdata.module, line 706 - yr_verdata.module This file provides the yr_verdata forecast module.
Code
function _yr_verdata_xml($url) {
$comps = explode('/', $url);
switch ($comps[0]) {
case 'place':
$xml = 'forecast.xml';
break;
case 'sted':
$xml = 'varsel.xml';
break;
case 'stad':
$xml = 'varsel.xml';
break;
}
// end switch lang
$remote_file = check_url('http://www.yr.no/' . drupal_urlencode($url) . '/' . $xml);
$local_dir = file_directory_path() . '/yr_verdata';
file_check_directory($local_dir, 1);
$local_file = $local_dir . '/' . implode('_', $comps) . '.xml';
$success = FALSE;
$local_file_age = @filemtime($local_file);
$now = time();
$maxage = variable_get('yr_verdata_maxage', 21600);
$timeout = 10;
if ($maxage > 0 && $now - $local_file_age > $maxage) {
if (function_exists('curl_init')) {
$c_handle = curl_init();
curl_setopt($c_handle, CURLOPT_URL, $remote_file);
curl_setopt($c_handle, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($c_handle);
$valid_xml = simplexml_load_string($data);
$c_info = curl_getinfo($c_handle);
if ($c_info['http_code'] != '200' || $c_info['size_download'] < 5000 || !$valid_xml) {
// If the server is unresponsive, or down for maintenance, we provide an error.
drupal_set_message(t('The file retrieved from @url was not a valid XML-file for this data type. This may be because yr.no is down for maintenance. Also, make sure that the location you specified is spelled correctly.', array(
'@url' => $remote_file,
)), 'warning');
watchdog('yr_verdata', 'The file retrieved from @url was not a valid XML-file for this data type. This may be because yr.no is down for maintenance. Also, make sure that the location you specified is spelled correctly.', array(
'@url' => $remote_file,
));
$success = FALSE;
}
else {
// The server returned http = 200, we assume we can load the xml data.
$f_handle = fopen($local_file, 'w');
curl_setopt($c_handle, CURLOPT_FILE, $f_handle);
curl_setopt($c_handle, CURLOPT_HEADER, 0);
curl_setopt($c_handle, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($c_handle, CURLOPT_TIMEOUT, $timeout);
curl_exec($c_handle);
fclose($f_handle);
$success = TRUE;
}
curl_close($c_handle);
}
else {
if ($message == 1) {
drupal_set_message(t('No method for retrieving forecast data was found. You must have PHP 5 with cURL available.'), 'error');
}
watchdog('yr_verdata', 'Could not retrieve remote XML data from @url, because cURL was not found.', array(
'@url' => $remote_file,
));
$success = FALSE;
}
}
else {
$success = 'not maxage';
}
return $success;
}