How to show Weather using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to show Weather using PHP

Post by Tony » Sun Nov 29, 2009 4:18 am

Get ad-free weather conditions from the National Oceanic and Atmospheric Administration. This following script can be used as an example and modified to fit your site. Instructions are embedded in comments in the script.
w.PNG
w.PNG (17.38 KiB) Viewed 2897 times

Code: Select all

<?php
// get the available xml file name for your area from
// http://www.weather.gov/data/current_obs/
$xmlFile = 'http://www.weather.gov/data/current_obs/KTPA.xml';
$weatherArray = @simplexml_load_file($xmlFile);
echo "<div style='width: 300px; padding: 20px; padding-bottom: 0px; margin: auto; border: solid 1px blue; font-size: 16px;'>";
if (!empty($weatherArray)) {
  $image = $weatherArray->icon_url_base . $weatherArray->icon_url_name;
  $alt = $weatherArray->weather;
  echo "<img src='$image' alt='$alt' style='float: left; margin-right: 20px;' />
    <b>$weatherArray->weather</b><br />
    <b>$weatherArray->temperature_string</b><br /><br /><br />
    The wind is <b>$weatherArray->wind_string</b><br />
    The wind chill is <b>$weatherArray->windchill_string</b><br />
    The visibility is <b>$weatherArray->visibility_mi miles</b><br />
    The relative humidity is <b>$weatherArray->relative_humidity%</b><br />
    The dewpoint is <b>$weatherArray->dewpoint_string</b><br />
    The pressure is <b>$weatherArray->pressure_in\"</b>
    <p style='text-align: center; font-size: 12px'>$weatherArray->observation_time</p>
  ";
} else echo "<span style='color: firebrick; font-size: 14px;'>There was a problem loading the weather data file.<br /><br />Please try again later.<br /><br /></span>";
echo "</div>"; 
?>
If your site has a lot of traffic, then you may want to download the weather xml file every hour (it is only updated once an hour anyway) by using the following cron line and changing the script to read the local xml file.

15 * * * * GET http://www.nws.noaa.gov/data/current_obs/KTPA.xml > $HOME/public_html/KTPA.xml
Post Reply

Return to “PHP & MySQL”