Yahoo! Weather RSS PHP Script
I needed a simple script to pull the weather conditions for a particular zip code. I search and found nothing, so I wrote the script below. It uses CURL to pull the Yahoo! Weather RSS feed, then uses SimpleXMLElement and XPath to pull the specific elements that I needed. Since the script does return the entire RSS feed, it would be simple to add lines to pull additional information if needed. Note that it uses PHP short-tags to display the final information… I loath using PHP to generate XHTML.
And for the curious, the default location is Fullerton, California… birthplace of the Fender guitar and this script.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Yahoo! Weather API RSS</title>
<?php
function retrieveYahooWeather($zipCode="92832") {
$yahooUrl = "http://weather.yahooapis.com/forecastrss";
$yahooZip = "?p=$zipCode";
$yahooFullUrl = $yahooUrl . $yahooZip;
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$yahooFullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
return $returnYahooWeather;
}
$localZipCode = "92352"; // Lake Arrowhead, CA
$weatherXmlString = retrieveYahooWeather($localZipCode);
$weatherXmlObject = new SimpleXMLElement($weatherXmlString);
$currentCondition = $weatherXmlObject->xpath("//yweather:condition");
$currentTemperature = $currentCondition[0]["temp"];
$currentDescription = $currentCondition[0]["text"];
?>
</head>
<body>
<h1>Lake Arrowhead, California</h1>
<ul>
<li>Current Temperature: <?=$currentTemperature;?>°F</li>
<li>Current Description: <?=$currentDescription;?></li>
</ul>
</body>
</html>
About this entry
You’re currently reading “Yahoo! Weather RSS PHP Script,” an entry on Wercshop
- Published:
- 06.11.08 / 5pm
- Category:
- PHP, Tips & Tricks, Web
1 Comment
Jump to comment form | comments rss [?] | trackback uri [?]