Skip to content

Instantly share code, notes, and snippets.

@joshhartman
Created April 1, 2012 04:54
Show Gist options
  • Save joshhartman/2271523 to your computer and use it in GitHub Desktop.
Save joshhartman/2271523 to your computer and use it in GitHub Desktop.
Yahoo! Weather API Example Using SimpleXML in PHP
<?php
if(isset($_POST['zipcode']) && is_numeric($_POST['zipcode'])){
$zipcode = $_POST['zipcode'];
}else{
$zipcode = '50644';
}
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=f');
$xml = simplexml_load_string($result);
//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');
if(!empty($location)){
foreach($xml->channel->item as $item){
$current = $item->xpath('yweather:condition');
$forecast = $item->xpath('yweather:forecast');
$current = $current[0];
$output = <<<END
<h1 style="margin-bottom: 0">Weather for {$location[0]['city']}, {$location[0]['region']}</h1>
<small>{$current['date']}</small>
<h2>Current Conditions</h2>
<p>
<span style="font-size:72px; font-weight:bold;">{$current['temp']}&deg;F</span>
<br/>
<img src="http://l.yimg.com/a/i/us/we/52/{$current['code']}.gif" style="vertical-align: middle;"/>&nbsp;
{$current['text']}
</p>
<h2>Forecast</h2>
{$forecast[0]['day']} - {$forecast[0]['text']}. High: {$forecast[0]['high']} Low: {$forecast[0]['low']}
<br/>
{$forecast[1]['day']} - {$forecast[1]['text']}. High: {$forecast[1]['high']} Low: {$forecast[1]['low']}
</p>
END;
}
}else{
$output = '<h1>No results found, please try a different zip code.</h1>';
}
?>
<html>
<head>
<title>Weather</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
}
label {
font-weight: bold;
}
</style>
</head>
<body>
<form method="POST" action="">
<label>Zip Code:</label> <input type="text" name="zipcode" size="8" value="" /><br /><input type="submit" name="submit" value="Lookup Weather" />
</form>
<hr />
<?php echo $output; ?>
</body>
</html>
@paulazh
Copy link

paulazh commented Mar 24, 2016

Amazing!! thank you.

@Nitrotoxin
Copy link

doesn't work =(
Warning: file_get_contents(http://weather.yahooapis.com/forecastrss?p=50644&u=f): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized in C:\xampp\htdocs\weather.php on line 7

Did they change the yahoo weather api recently?

@ixlipixli
Copy link

I am having the same problem. The code is not working anymore.

@ntsasng
Copy link

ntsasng commented Mar 29, 2016

Same issue.

@Dzonny
Copy link

Dzonny commented Mar 31, 2016

Shame to see this happened. Any chance for the alternative script maybe?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment