Twitter Weather in PHP
Update: I’ve made Twitter Weather, an easy to use site where you put in your twitter username/password, the zip code you want weather for, and the time to publish it.
I’ve just started using Twitter (add me as a friend) and it’s great! The first thing I wanted when I joined was to get daily weather reports at 7 AM, so I wrote a silly PHP script to do it, the source code to which you can see below (apologies if the formatting is bad):
<?php
$uname = 'nyc_weather';
$pwd = 'ThePassWordHere';
$twitter_url = 'http://twitter.com/statuses/update.xml';
$feed = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
error_reporting(E_ALL);
// <yweather:forecast day="Thu"…
$data = file_get_contents($feed);
preg_match('`<yweather:forecast day="(.*?)" date="(.*?)" low="(.*?)" high="(.*?)" text="(.*?)"[^>]*>`si', $data, $w);
// make the status
$status = urlencode("The forecast for $w[1], $w[2] is $w[5]. High: $w[4] F Low: $w[3] F.");
//just for status if you are directly viewing the script
echo $status;
// send it off
$curl_handle = curl_init();
curl_setopt($curl_handle,CURLOPT_URL,"$twitter_url");
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle,CURLOPT_POST,1);
curl_setopt($curl_handle,CURLOPT_POSTFIELDS,"status=$status");
curl_setopt($curl_handle,CURLOPT_USERPWD,"$uname:$pwd");
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer))
echo '<br/>message';
else
echo '<br/>success';
?>
Then you just work a little crontab magic:
[root@fc435152 twitter]# crontab -l
0 7 * * * php /home/twitter/twitter-weather.php
And every day I get a Twitter message on the nyc_weather user (you can subscribe too if you’re from NY) like this:
The forecast for Wed, 04 Apr 2007 is Rain/Thunder. High: 46 F Low: 38 F.
I’m thinking of making a more generic service where you give my server your user, password, location, and time of day, and every day at that time (normalize to the local regional time of course) it will try to send the twitter update. I’d want to bake in retry, so it will keep retrying the old twitters. That’s a 1-2 day project, we’ll see.
| This entry was posted on Wednesday, April 4th, 2007 at 9:49 am and is tagged with generic service, weather reports, statuses, php script, twitter, apologies, lt, formatting, source code, exec, crontab, zip code, rain. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback. |
2 Responses to “Twitter Weather in PHP”
Leave a Reply



[...] I have fast become a fan of Twitter over other social networking tools, however one thing I would just love to see is a Twitter setup for my local weather! Well the other day I happened upon this tool that pings Twitter using the provided PHP code as you see in the article. [...]
Very cool service! I'm signed up and using it! Thanks so much!! twitter.com/slcweather