<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>PHP Starter &#187; Andrew</title>
	<atom:link href="http://phpstarter.net/author/andrew/feed/" rel="self" type="application/rss+xml" />
	<link>http://phpstarter.net</link>
	<description>PHP Tips &#38; Tools From Starters to Experts</description>
	<lastBuildDate>Fri, 25 Jun 2010 14:14:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Send Print Jobs Directly from PHP</title>
		<link>http://phpstarter.net/2010/05/send-print-jobs-directly-from-php/</link>
		<comments>http://phpstarter.net/2010/05/send-print-jobs-directly-from-php/#comments</comments>
		<pubDate>Wed, 19 May 2010 16:04:25 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=524</guid>
		<description><![CDATA[I recently learned that you can send print jobs directly from a PHP server. How cool is that? This article will cover sending print jobs from a PHP server to a printer on the same LAN. This does not mean that someone viewing a page over the Internet can have something print on their local [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>I recently learned that you can send print jobs directly from a PHP server.  How cool is that?  This article will cover sending print jobs from a PHP server to a printer on the same LAN.  This does <strong>not</strong> mean that someone viewing a page over the Internet can have something print on their local printer with these functions.  This <strong>does</strong> mean if you have PHP running on a Windows server in your internal network, you can print to printers that are configured on that Windows server <strong>only</strong>.</p>
<p><span id="more-524"></span></p>
<p>This article really only applies if you are hosting the web server in your local office or place of business.  If you are hosting your web server in a data center somewhere and you never see it, this article is probably not for you.  In the diagram below, pretend the server and attached printers are in your office building somewhere, and the computers in the red box are your clients out on the Internet somewhere.  Note that the printers at the client side are not used in this application.</p>
<p><img src="http://phpstarter.net/wp-content/uploads/2010/04/printing.png" alt="" title="Printing Diagram" width="600" height="400" class="aligncenter size-full wp-image-529" /></p>
<p>Another possible setup would be if everything is on a private internal network, like the diagram below.  In this case everything is in the green box because it is all on an internal network joined by a network switch.  The two printers are in yellow boxes because they are only visible to the server if shared from those attached network computers, and the computers are turned on.</p>
<p><img src="http://phpstarter.net/wp-content/uploads/2010/04/printing_lan.png" alt="" title="Printing Diagram - LAN" width="600" height="400" class="aligncenter size-full wp-image-529" /></p>
<p>So now that we have the big picture, there are a couple other things to note.  The web server needs to be running Windows, not Linux.  The PHP Printer functions are Windows only.  The printer(s) can be connected locally via USB/Parallel, over the network via IP JetDirect, or shared off of another server/computer.</p>
<h3>Printing Plain Text Documents</h3>
<p>Printing plain text documents are a piece of cake.  It&#8217;s going to be similar to echoing text out to the web browser with a couple differences.  This is the first test I did:</p>
<pre class="brush: php">
&lt;?php
	/* get the sample text */
	$lipsum = file_get_contents(&#039;lipsum.txt&#039;);

	/* open a connection to the printer */
	$printer = printer_open(&quot;Lexmark X850e XL V&quot;);

	/* write the text to the print job */
	printer_write($printer, $lipsum);

	/* close the connection */
	printer_close($printer);
?&gt;
</pre>
<p>The printer in line 6 is in my <a href="/wp-content/uploads/2010/04/printers.png">windows printer list</a>, and has to be matched exactly.  That function can be called without a printer parameter, and PHP will use the default printer specified in php.ini or try to detect it based on how it is set in Windows.  I wanted to do close to a full page of text, so I went to <a href="http://www.lipsum.com/">lipsum.com</a> and generated some sample text and saved it to a <a href="/samples/524/lipsum.txt">text file</a>.</p>
<p>So here is the <a href="/wp-content/uploads/2010/04/printer_test.jpg">printed result</a>, and the cool thing is that the text was almost exactly a full page.  The not-so-cool thing was that it doesn&#8217;t do simple things like word wrap.  Luckily, we can run the text through <a href="http://us2.php.net/manual/en/function.wordwrap.php">wordwrap()</a> before sending it to the printer to easily fix that.</p>
<p class="m_info">For future examples, I will be using my <a href="http://sourceforge.net/projects/pdfcreator/">PDFCreator</a> printer so I don&#8217;t waste paper (or money) during testing, and I encourage you to do the same.</p>
<h3>Printing a Custom Font</h3>
<p>If you want to print with a custom font, it is done using functions that are similar to the <a href="/tag/gd-library/">GD Library</a> functions.  You need to define the font, X/Y position, and other font weight properties.</p>
<p>In this example, I&#8217;m going to use the <a href="http://www.barcodesinc.com/free-barcode-font/">freely available barcode font</a> to print a barcode on a piece of paper.  In this example, I am also going to define the printer document and the individual page.</p>
<pre class="brush: php">
&lt;?php
	/* get the sample text */
	$lipsum = file_get_contents(&#039;lipsum.txt&#039;);

	/* open a connection to the printer */
	$printer = printer_open(&quot;PDFCreator&quot;);
	printer_start_doc($printer, &quot;Doc&quot;);
	printer_start_page($printer);

	/* font management */
	$barcode = printer_create_font(&quot;Free 3 of 9 Extended&quot;, 400, 200, PRINTER_FW_NORMAL, false, false, false, 0);
	$arial = printer_create_font(&quot;Arial&quot;, 148, 76, PRINTER_FW_MEDIUM, false, false, false, 0);

	/* write the text to the print job */
	printer_select_font($printer, $barcode);
	printer_draw_text($printer, &quot;*123456*&quot;, 50, 50);
	printer_select_font($printer, $arial);
	printer_draw_text($printer, &quot;123456&quot;, 250, 500);

	/* font management */
	printer_delete_font($barcode);
	printer_delete_font($arial);

	/* close the connection */
	printer_end_page($printer);
	printer_end_doc($printer);
	printer_close($printer);
?&gt;
</pre>
<h3>Drawing Images</h3>
<p>The printer functions only support writing bitmaps (bmp), so you will have to convert the images to that format before using it in this application.  The X,Y parameters in the printer_draw_bmp() function are in inches.</p>
<pre class="brush: php">
&lt;?php
	/* open a connection to the printer */
	$printer = printer_open(&quot;PDFCreator&quot;);
	printer_start_doc($printer, &quot;Doc&quot;);
	printer_start_page($printer);

	/* draw the image to the page */
	printer_draw_bmp($printer, &quot;c:\\path\\to\\image.bmp&quot;, 1, 1);

	/* close the connection */
	printer_end_page($printer);
	printer_end_doc($printer);
	printer_close($printer);
?&gt;
</pre>
<h3>Drawing Shapes</h3>
<p>Several shapes can be drawn as well.  The example will show two horizontal &#038; parallel lines of different length.</p>
<pre class="brush: php">
&lt;?php
	/* open a connection to the printer */
	$printer = printer_open(&quot;PDFCreator&quot;);
	printer_start_doc($printer, &quot;Doc&quot;);
	printer_start_page($printer);

	/* create the pen handle and set some properties */
	$pen = printer_create_pen(PRINTER_PEN_SOLID, 30, &quot;000000&quot;);
	printer_select_pen($printer, $pen);

	/* draw some lines on the page */
	printer_draw_line($printer, 1, 100, 1000, 100);
	printer_draw_line($printer, 1, 200, 500, 200);

	/* delete the pen handle */
	printer_delete_pen($pen);

	/* close the connection */
	printer_end_page($printer);
	printer_end_doc($printer);
	printer_close($printer);
?&gt;
</pre>
<h3>Practical Uses</h3>
<p>Couple uses come to mind, and I&#8217;m sure there are others (post them if you have a good one!).</p>
<ul>
<li>Automatically print packing slips / invoices at a shipping center as customers place orders.</li>
<li>On an intranet website, have all the company printers configured at the server side so users can use the web application w/o worrying about setting up the printers at their workstation.</li>
<li>Automatically printing out reports generated by a CLI PHP script</li>
</ul>
<p>For more information, check out <a href="http://us.php.net/manual/en/book.printer.php">PHP print functions</a>.</p>
<h3>Printing from PHP on Linux Servers</h3>
<p>&#8220;But what about Linux servers!&#8221;, you say.  Well, as previously stated, the PHP functions don&#8217;t support anything other than Windows, but there is an alternative.  PHP4IT.com has an article titled <a href="http://php4it.com/a-1.html">Printing a form directly to a PCL printer (Linux)</a> that should help you with manually building the Postscript file and writing it through to the printer.  That should help get you started.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2010/05/send-print-jobs-directly-from-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Making Google Static Maps a Little More Dynamic with PHP</title>
		<link>http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/</link>
		<comments>http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/#comments</comments>
		<pubDate>Wed, 17 Mar 2010 14:00:24 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=501</guid>
		<description><![CDATA[If you have messed with the Google Maps API, you know that the JavaScript and API keys can be a real headache. Yes, there are very complex implementations that you can use, but what if you want&#8230;just a map? If you want just a map with no dynamic interface, Google Static Maps is just for [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>If you have messed with the <a href="http://code.google.com/apis/maps/">Google Maps API</a>, you know that the JavaScript and API keys can be a real headache.  Yes, there are <a href="http://www.wunderground.com/wundermap/">very</a> <a href="http://www.packagemapping.com/">complex</a> <a href="http://sites.google.com/site/gmapsmania/100thingstodowithgooglemapsmashups">implementations</a> that you can use, but what if you want&#8230;just a map?  If you want just a map with no dynamic interface, Google Static Maps is just for you.  I will show how easy it is to use, and then spice it up with some PHP-powered enhancements.</p>
<p><span id="more-501"></span></p>
<p>Check out how easy this is.  If I want a map centered at a my zip code, I can create a JPEG image for that area with this link:</p>
<p><code>http://maps.google.com/maps/api/staticmap?sensor=false&#038;center=46311&#038;zoom=14&#038;size=600x400</code></p>
<p>And it generates this:</p>
<p><img src="http://maps.google.com/maps/api/staticmap?sensor=false&#038;center=46311&#038;zoom=14&#038;size=600x400" alt="" /></p>
<p>No API keys, no JavaScript, and the URL is even short enough to not have to wrap on the page.  As long as you don&#8217;t need the typical panning and zooming features, this is the best option.  There are a limited but practical set of features including map types (satellite, hybrid, regular, etc), markers, lines, shapes, custom icons, and all in different image formats.  View the <a href="http://code.google.com/apis/maps/documentation/staticmaps/">Google Static Maps API</a> page for the full details.</p>
<h3>Making it a Little More Dynamic</h3>
<p>This is a site on PHP.  I can&#8217;t show you how to create static maps and leave it at that.  There are several good reasons why we might want to dynamically generate that URL. </p>
<p><b>Simple &#8220;You Are Here&#8221; Map</b></p>
<p>For starters, how about a map that shows your local area based on your IP address geolocation?  This sample below uses the code from a previous article that showed how to <a href="http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/">determine the geographic location from any IP address</a>.</p>
<p style="text-align: right; "><a href="/samples/501/geoip.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id and info */
$query = &quot;SELECT CityLocation.* FROM CityBlocks INNER JOIN CityLocation ON CityLocation.locId = CityBlocks.locId WHERE $ip BETWEEN CityBlocks.startIpNum AND CityBlocks.endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

?&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Static Map for Your Location&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;Static map for your town:&lt;/h2&gt;
&lt;p&gt;If you are placed in the middle of an ocean, your IP address is probably not in the database.  The blue marker is your specific IP location (probably not exact).&lt;/p&gt;
&lt;img src=&quot;http://maps.google.com/maps/api/staticmap?sensor=false&amp;center=&lt;?=$location['postalCode']?&gt;&amp;markers=color:blue|&lt;?=$location['latitude']?&gt;,&lt;?=$location['longitude']?&gt;&amp;zoom=13&amp;size=600x400&quot; /&gt;

&lt;h2&gt;Details from IP GeoLocation:&lt;/h2&gt;
&lt;pre&gt;&lt;?php var_dump($location); ?&gt;&lt;/pre&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><b>Show Your Position With Other Objects</b></p>
<p>We already know how to find a list of the closest items in our area from this post: <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">Locate the Nearest Radar Station and Display Radar Images</a>.  Now, let&#8217;s apply it to generating a Static Google Map.  This uses the &#8220;Implicit Positioning&#8221; feature where you can just list a bunch of points, and the map will automatically create a zoom level and center based on the created points.</p>
<p style="text-align: right; "><a href="/samples/501/radar_sites.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks 
			WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 5&quot;;
$result = mysql_query($query, $db) or die(mysql_error());

$qs = '';
for ($i = 0; $i &lt; mysql_num_rows($result); $i++)
{
	$row = mysql_fetch_assoc($result);
	$rows[] = $row;
	
	/* remember - we want roughly the center of the radar coverage, not the top-left corner */
	$lat = $row['lat'] - 3;
	$lon = $row['lon'] + 3;
	
	/* forming the query string for the image URL */
	$markers[] = '&amp;markers=color:blue|label:' . $i . '|' . $lat . ',' . $lon;
}

$markers = implode('', $markers);

?&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Static Map for Your Location&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;5 Closest Radar Sites to You&lt;/h2&gt;
&lt;p&gt;Red marker is you.&lt;/p&gt;
&lt;img src=&quot;http://maps.google.com/maps/api/staticmap?sensor=false&amp;maptype=roadmap&lt;?=$markers?&gt;&amp;markers=color:red|&lt;?=$location['latitude']?&gt;,&lt;?=$location['longitude']?&gt;&amp;size=600x400&quot; /&gt;

&lt;h2&gt;Details from IP GeoLocation:&lt;/h2&gt;
&lt;pre&gt;&lt;?php var_dump($location); ?&gt;&lt;/pre&gt;

&lt;h2&gt;Radar Sites:&lt;/h2&gt;
&lt;pre&gt;&lt;?php var_dump($rows); ?&gt;&lt;/pre&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>These examples are meant to get your creative juices flowing.  Have some other cool concepts for Google Static Maps?  Post them below.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2010/03/making-google-static-maps-a-little-more-dynamic-with-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Parse ZFP (Zone Forecast Product) Data in PHP &#8211; Option 1</title>
		<link>http://phpstarter.net/2010/03/parse-zfp-zone-forecast-product-data-in-php-option-1/</link>
		<comments>http://phpstarter.net/2010/03/parse-zfp-zone-forecast-product-data-in-php-option-1/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 14:00:59 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Weather]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=449</guid>
		<description><![CDATA[In a previous article, I covered 5 Sources of Free Weather Data for your Site, but did not provide any actual code to use the data. Since then, I covered sources #1 and #2. None of these sources had any English-formed forecasts. For that, we have to go to the Zone Forecast Product, but we [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>In a previous article, I covered <a href="http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/">5 Sources of Free Weather Data for your Site</a>, but did not provide any actual code to use the data.  Since then, I covered sources <a href="http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/">#1</a> and <a href="http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/">#2</a>.  None of these sources had any English-formed forecasts.  For that, we have to go to the Zone Forecast Product, but we don&#8217;t have the luxury of XML here.  There is a healthy bit of RegEx and string manipulation, but you can do it!</p>
<p><span id="more-449"></span></p>
<h3>Where to Get the Data</h3>
<p>The data is available by browsing the <a href="http://www.weather.gov/data/">http://www.weather.gov/data/</a> directory.  Here, you will find a whole set of products available.  To access the ZFP data, you need to browse the http://www.weather.gov/data/XXX/ZFPXXX directory where &#8216;XXX&#8217; is the code for the local station from where the data is to be retrieved from.  For example, if I wanted the ZFP data for KLOT (Lockport, IL), I would call up <a href="http://www.weather.gov/data/LOT/ZFPLOT">http://www.weather.gov/data/LOT/ZFPLOT</a>.</p>
<p class="m_warning">There is an exception to this rule, however.  If you look at <a href="http://www.weather.gov/data/AFC/">http://www.weather.gov/data/AFC/</a>, they show the ZFP for two areas.  I think some of these are like this because one office is forecasting for to areas or something (correct me in the comments if I&#8217;m wrong).  So that formula above is more of a guideline for finding the right link for your area, but I found it to be 95% accurate.  (That&#8217;s still an &#8216;A&#8217;, right?)</p>
<h3>Understanding the Big Picture</h3>
<p><a href="http://phpstarter.net/wp-content/uploads/2009/07/zfp_01.png"><img src="http://phpstarter.net/wp-content/uploads/2009/07/zfp_01-150x150.png" alt="zfp_01" title="zfp_01" width="150" height="150" class="alignnone size-thumbnail wp-image-470" style="float: left; margin-right: 10px; " /></a></p>
<p>Click on the thumbnail for the explained section of this data.  Starting at the top is the header.  We don&#8217;t use this.  It contains the station ID and the type of product this is &#8211; we know that already.  It also contains the release time.  Although that is significant, that same information is in the header of the individual forecasts as well, so I will be discarding that in this example.</p>
<p>The second yellow box is the header for that specific forecast zone.  We will be using some data from this.  The zone code is the most critical because we need to know for which zone this forecast is for.  The only other piece of information in this box that I use is the Release Time, which is when the forecast was released (ironic).  This block of information is repeated at the top of every forecast in the file.</p>
<p>Below the second yellow box is the actual forecast data, which is the meat of what we are looking for.  Below that is the separator, which is means that the code block for the next forecast zone is next, and so on&#8230;</p>
<h3>Breaking up the Forecasts</h3>
<p>We only want to deal with one forecast zone at a time, so lets break them up.  First, I need to get rid of that pesky header at the top of the file.  We do that by splitting the data by the double line breaks, and removing that first paragraph from the resulting array.  Then, join it back together.</p>
<pre class="brush: php">
/* remove the file header */

/* $data = {text from http://www.weather.gov/data/LOT/ZFPLOT} */

$data = trim($data);
$data = explode(&quot;\n\n&quot;, $data);
unset($data[0], $data[1]);
$data = implode(&quot;\n\n&quot;, $data);
</pre>
<p>Now, we can split of the zone forecasts.  We simply split the text by the separator (&#8216;$$&#8217;), and keep the forecasts in an array.</p>
<pre class="brush: php">
/* separate the forecasts */

/* $data = {result from previous example} */

$data = explode(&#039;$$&#039;, $data);
/* trim off any extra line breaks */
$data = array_map(&#039;trim&#039;, $data);
</pre>
<p>Perfect.  Now we have an array or forecasts with their respective header block.</p>
<h3>Parsing the Zone Codes</h3>
<p>This is the hardest part of understanding the data.  We need to know for which geographical area the forecast is for.  Most zone forecasts are only for one zone, but it is possible that it may be for more than one.  In the above example, the zone code is ILZ014, which is zone 14 of Illinois.  Unfortunately, the zone code &#038; purge date line can be as complicated as <em>ILZ001>003-005-IAC045-163-051200-</em>, which is Illinois zone 1, 2, 3, 5 as well as Iowa counties 45 and 163.  For the full specs on how to understand this, see the <a href="http://www.weather.gov/emwin/winugc.htm">Universal Geographic Code</a> specifications.</p>
<p>Before we can do anything, we need to find the zone codes.  To do that, we need to use one heck of a regular expression, found on line 8 of the sample below.  This is what I used to verify that I am finding everything correctly.</p>
<p style="text-align: right; "><a href="/samples/449/zone_codes.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* get the forecast from a local cache */
/* http://www.weather.gov/data/LOT/ZFPLOT */
$data = file_get_contents('ZFPIND.txt');

/* the regular expression to find all the location codes */
$regex = '/(([A-Z]{2})(C|Z){1}([0-9]{3})((&gt;|-)[0-9]{3})*)-/';

/* for this example, we are doing a replacement to show we found everything...
	normally, something like preg_match() would be used */
$data = preg_replace($regex, '&lt;span style=&quot;background: #ff0; &quot;&gt;' . &quot;\${1}&quot; . '&lt;/span&gt;-', $data);

/* do I really need to explain this? */
echo '&lt;pre&gt;' . $data . '&lt;/pre&gt;';

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>We&#8217;re not done with this yet.  As you can see from the <a href="http://www.weather.gov/emwin/winugc.htm">Universal Geographic Code</a> reference page, they like to make shortcuts.  For example, they will use <em>INZ021-028>031</em> instead of <em>INZ021-INZ028-INZ029-INZ030-INZ031</em>.  From a programming standpoint, I think we both know which is better to understand.  When I put this data in a database, I need to be able to query a specific location and see if there is data for it.  So, if I store it as <em>INZ021-028>031</em>, how do I query for zone 29?  These ranges will have to be expanded.</p>
<p>I&#8217;m not going to go into great detail on how to do this&#8230;I will just provide a couple functions to do it.  Call parse_zones() like I do at line 69, and it will take care of the rest.</p>
<p style="text-align: right; "><a href="/samples/449/parse_zones.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php

/**
 * The NWS combines does not repeat the state code for multiple zones...not good for our purpose
 * All we want to do here is convert ranges like INZ021-028 to INZ021-INZ028
 * We will also call the function to expand the ranges here.
 * See: http://www.weather.gov/emwin/winugc.htm
 */
function parse_zones($data)
{
	/* first, get rid of newlines */
	$data = str_replace(&quot;\n&quot;, '', $data);
	
	/* split up individual states - multiple states may be in the same forecast */
	$regex = '/(([A-Z]{2})(C|Z){1}([0-9]{3})((&gt;|-)[0-9]{3})*)-/';
	
	$count = preg_match_all($regex, $data, $matches);
	$total_zones = '';
	
	foreach ($matches[0] as $field =&gt; $value)
	{
		/* since the NWS thought it was efficient to not repeat state codes, we have to reverse that */
		$state = substr($value, 0, 3);
		$zones = substr($value, 3);
		
		/* convert ranges like 014&gt;016 to 014-015-016 */
		$zones = expand_ranges($zones);
		
		/* hack off the last dash */
		$zones = substr($zones, 0, strlen($zones) - 1);
		$zones = $state . str_replace('-', '-'.$state, $zones);
		
		$total_zones .= $zones;
	}
	
	
	$total_zones = explode('-', $total_zones);
	return $total_zones;
}

/**
 * The NWS combines multiple zones into ranges...not good for our purpose
 * All we want to do here is convert ranges like 014&gt;016 to 014-015-016
 * See: http://www.weather.gov/emwin/winugc.htm
 */
function expand_ranges($data)
{
	$regex = '/(([0-9]{3})(&gt;[0-9]{3}))/';
	
	$count = preg_match_all($regex, $data, $matches);
	
	foreach ($matches[0] as $field =&gt; $value)
	{
		list($start, $end) = explode('&gt;', $value);
		
		$new_value = array();
		for ($i = $start; $i &lt;= $end; $i++)
		{
			$new_value[] = str_pad($i, 3, '0', STR_PAD_LEFT);
		}
		
		$data = str_replace($value, implode('-', $new_value), $data);
	}
	
	return $data;
}


$zones = parse_zones(&quot;INZ021-028&gt;031-035-036-190915-&quot;);

header('Content-type: text/plain');
var_dump($zones);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<h3>Putting it All Together</h3>
<p>So we know how to download the latest forecast data for a specific station, split it up, and get the zones for each one.  Now it&#8217;s time to put it together and in a format where we can store or display it.  In this example, I am adding some more basic PHP to form a large array with the forecast block and zones in each element.  From there, you can easily place the data in a database or whatever.</p>
<p class="m_info"><strong>Note:</strong> Note that I am using data from KIND and not KLOT in this example, because KIND has forecast blocks that cover multiple zones, showing how parse_zones() work.</p>
<p style="text-align: right; "><a href="/samples/449/zfp.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/**
 * adds the two functions from the previous example:
 * parse_zines()
 * parse_ranges()
 */
include('functions.php');

$data = file_get_contents('ZFPIND.txt');

/* remove the file header */
$data = trim($data);
$data = explode(&quot;\n\n&quot;, $data);
unset($data[0], $data[1]);
$data = implode(&quot;\n\n&quot;, $data);


/* separate the forecasts */
$data = explode('$$', $data);
/* trim off any extra line breaks */
$data = array_map('trim', $data);

$data_form = array();
foreach ($data as $field =&gt; $value)
{
	$lines = explode(&quot;\n&quot;, $value);
	$zones = parse_zones($lines[0]);
	
	$blocks = explode(&quot;\n\n&quot;, $value);
	$forecast = $blocks[1];
	
	$data_time = parse_date_time($value);
	
	$data_form[] = array('zones' =&gt; $zones, 'date_time' =&gt; $date_time, 'forecast' =&gt; $forecast);
}


header('Content-type: text/plain');
var_dump($data_form);


/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>After running the example, you will see that we have an array with several numbered elements.  Each element is a sub-array containing an array of zones and an element containing the forecast data.</p>
<p>So there you have it.  With one request to the NWS website, you can gather all the ZFP data for an entire forecast area.  Again, this is useful when you need to gather forecasts for the general area, not just one zone at a time.  If you only need to grab one zone at a time, stay tuned because I will be writing soon on how to make use of an easier data source that grabs one zone at a time that makes for easier parsing on your part.</p>
<h3>Making it Look Pretty</h3>
<p><strong>Another teaser for a future article</strong>&#8230;Once you find the page containing the data you want to work with, it looks like an undaunted task to turn that data into something presentable.  Let me assure you right off the bat that it is doable with a healthy bit of string manipulation and regular expressions.  Just for a bit of comparison, you should be able to turn <a href="http://www.weather.gov/data/LOT/ZFPLOT">this</a> into <a href="http://chasingweather.com/forecast/lat_lon/41.9288/-87.6315#zone-forecast">this</a>.  How do we split up the days and add the cool icons?  I will cover that in the next article.  To be continued&#8230;</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2010/03/parse-zfp-zone-forecast-product-data-in-php-option-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Merge Image Layers in PHP</title>
		<link>http://phpstarter.net/2009/07/merge-image-layers-in-php/</link>
		<comments>http://phpstarter.net/2009/07/merge-image-layers-in-php/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 12:00:40 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[Weather]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=455</guid>
		<description><![CDATA[In a previous article, I showed how to Locate the Nearest Radar Station and Display Radar Images. A commenter, mike, pointed out the idea of merging the image layers using PHP instead of layering all the images separately using CSS. Here is how to do it. Just like the previous article on finding the closest [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>In a previous article, I showed how to <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">Locate the Nearest Radar Station and Display Radar Images</a>.  A commenter, <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/comment-page-1/#comment-332">mike</a>, pointed out the idea of merging the image layers using PHP instead of layering all the images separately using CSS.  Here is how to do it.</p>
<p><span id="more-455"></span></p>
<p>Just like the previous article on finding the closest radar station, I am going to use <a href="http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/">IP geolocation</a> to find the closest radar site.  See that <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">previous article</a> for an explanation on how to do that.</p>
<p style="text-align: right; "><a href="/samples/455/radar_combined.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks 
			WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$radar = mysql_fetch_assoc($result);

/* we are using the snoopy class to download the images */
include('../includes/Snoopy.class.php');
$snoopy = new Snoopy();

/* cache the files locally */
function dl_cache($url, $filename)
{
	if (!file_exists($filename) || filemtime($filename) + 600 &lt; time())
	{
		global $snoopy;
		$snoopy-&gt;fetch($url);
		file_put_contents($filename, $snoopy-&gt;results);
		$snoopy-&gt;results = '';
	}
}

/* download the radar images */
$radar_id = $radar['id'];
dl_cache(&quot;http://radar.weather.gov/Overlays/Topo/Short/{$radar_id}_Topo_Short.jpg&quot;, &quot;maps/{$radar_id}_Topo_Short.jpg&quot;);
dl_cache(&quot;http://radar.weather.gov/RadarImg/N0R/{$radar_id}_N0R_0.gif&quot;, &quot;maps/{$radar_id}_N0R_0.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/County/Short/{$radar_id}_County_Short.gif&quot;, &quot;maps/{$radar_id}_County_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/Highways/Short/{$radar_id}_Highway_Short.gif&quot;, &quot;maps/{$radar_id}_Highway_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/Rivers/Short/{$radar_id}_Rivers_Short.gif&quot;, &quot;maps/{$radar_id}_Rivers_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Overlays/Cities/Short/{$radar_id}_City_Short.gif&quot;, &quot;maps/{$radar_id}_City_Short.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Legend/N0R/{$radar_id}_N0R_Legend_0.gif&quot;, &quot;maps/{$radar_id}_N0R_Legend_0.gif&quot;);
dl_cache(&quot;http://radar.weather.gov/Warnings/Short/{$radar_id}_Warnings_0.gif&quot;, &quot;maps/{$radar_id}_Warnings_0.gif&quot;);

/* load the radar layers into an array */
$layers = array();
$layers[] = imagecreatefromjpeg(&quot;maps/{$radar_id}_Topo_Short.jpg&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_N0R_0.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_County_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_Highway_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_Rivers_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_City_Short.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_N0R_Legend_0.gif&quot;);
$layers[] = imagecreatefromgif(&quot;maps/{$radar_id}_Warnings_0.gif&quot;);

$image = imagecreatetruecolor(600, 550);


/* merge the layers */
for ($i = 0; $i &lt; count($layers); $i++)
{
	imagecopy($image, $layers[$i], 0, 0, 0, 0, 600, 550);
}

/* we're done! output the image... */
header('Content-type: image/jpeg');
imagejpeg($image);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>The code from line ~31 on is pretty self-explanatory.  Basically, I am caching the maps locally, and then loading the images into PHP image resources.  I am putting the images in a PHP array because I want to make it easy add/delete/move layers.  For the application I&#8217;m using it for, it&#8217;s not likely, but your needs may differ.</p>
<p>The important function is imagecopy(), which is defined as:</p>
<p><em>bool imagecopy  ( resource $dst_im  , resource $src_im  , int $dst_x  , int $dst_y  , int $src_x  , int $src_y  , int $src_w  , int $src_h  )</em></p>
<p>Since I am copying whole pictures directly on top of each other &#8211; all the same size &#8211; it&#8217;s very easy.  You can specify image sizes and location in case you are copying a smaller image onto a larger image, like a logo copyright on a photo, for example.</p>
<p>So there you have it.  Although I believe the first method of layering the images via CSS works just fine, this method will work when you need to deliver a single image.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/07/merge-image-layers-in-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Loading INI Files in PHP</title>
		<link>http://phpstarter.net/2009/04/loading-ini-files-in-php/</link>
		<comments>http://phpstarter.net/2009/04/loading-ini-files-in-php/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 12:00:23 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=424</guid>
		<description><![CDATA[PHP parses the php.ini file for the global PHP settings, but you can create an INI file that is specific to your own PHP application. You can also load those settings into as associate array with a native PHP function. How cool is that? Why? Having your config settings in a INI file makes it [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>PHP parses the php.ini file for the global PHP settings, but you can create an INI file that is specific to your own PHP application.  You can also load those settings into as associate array with a native PHP function.  How cool is that?</p>
<p><span id="more-424"></span></p>
<h3>Why?</h3>
<p>Having your config settings in a INI file makes it easier to edit, especially for those that don&#8217;t have PHP experience.  It also comes in handy if you have protected PHP scripts, and you want someone to have the option of changing settings without having access to any of the PHP code.  There are a couple negative effects though.  Obviously, there is going to be some performance overhead because PHP will have to parse this file for each and every request made by a site visitor.  Also, you can&#8217;t assign any dynamic values here, like time(), etc.  You will have to make the call to determine if this method is best for you.</p>
<h3>How it Works</h3>
<p>Below is a sample INI file that the later examples will be loading.  Notice the syntax used.  The double quotes are not needed, but I am in the habit of using them because they are required if any special characters are in the values.</p>
<pre class="brush: php">
;some general settings not related to anything else
[general]
home_url = &quot;http://www.example.com/&quot;
contact_email = &quot;contact@example.com&quot;
app_path = &quot;/path/to/app/root&quot;
name = &quot;application name&quot;

;settings required to connect to a MySQL database
[database]
host = &quot;localhost&quot;
name = &quot;database_name&quot;
user = &quot;db_user&quot;
pass = &quot;db_password&quot;

;show we can have an array
[arrays]
test[] = &quot;value1&quot;
test[] = &quot;value2&quot;
test[] = &quot;value3&quot;
</pre>
<p>In the first load example, we are going to load all of the settings in one block.  In other words, we are going to ignore the sections, defined in the &#8216;[ ]&#8216; characters.</p>
<p style="text-align: right; "><a href="/samples/424/parse.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* load the config file and dump the values  */
$config = parse_ini_file('sample.ini');

header('Content-type: text/plain');
var_dump($config);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>In the above example, we have a problem.  Notice that we have the setting &#8220;name&#8221; in more than one block, and because of that, we had a name conflict and lost one of the values.  To avoid this, we can put these setting blocks in their own associative array with the following statement.</p>
<p style="text-align: right; "><a href="/samples/424/parse_sep.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php

/* load the config settings and dump the values */
$config = parse_ini_file('sample.ini', true);

header('Content-type: text/plain');
var_dump($config);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>Now all the setting blocks are separated, and easily accessible.</p>
<p>So there you have it &#8211; a different type of configuration file that may be an option for your next PHP application.  It&#8217;s pretty simple, and you really only need one function call to load all the settings, so the learning curve is minimal.  If you want more information on this PHP function, check out the <a href="http://us3.php.net/parse_ini_file">function reference</a>.</p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/04/loading-ini-files-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Separating the Application &amp; Presentation and Alternative Syntax</title>
		<link>http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/</link>
		<comments>http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 16:31:47 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beginner]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=414</guid>
		<description><![CDATA[One of the biggest pet peeves I have when looking at (and unfortunately &#8211; working with) other people&#8217;s PHP code is the way they integrate their code into the HTML. Many people don&#8217;t take the time to organize, and they end up with a PHP &#038; HTML mess. I believe that it is critical to [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>One of the biggest pet peeves I have when looking at (and unfortunately &#8211; working with) other people&#8217;s PHP code is the way they integrate their code into the HTML.  Many people don&#8217;t take the time to organize, and they end up with a PHP &#038; HTML mess.  I believe that it is critical to separate the application logic from the presentation.  In other words &#8211; do the bulk of the application operations in a script file that has <strong>no text/HTML output</strong>.  When that processing is done, send the data to the presentation file that takes the data and outputs that along with the static HTML for that page.  In this article, I will present an easy way to do it using no template engines.</p>
<p><span id="more-414"></span></p>
<p>I have some perfect textbook examples that I would love to post of very badly-formatted code, but because of privacy and confidentially reasons with my clients, I can&#8217;t do that.  You will just have to take my word for it &#8211; I have seen some major hackjobs thrown together by the most obvious of n00bs I didn&#8217;t even know existed.</p>
<p>So the main thing to remember is this: Think of your web application as having two layers &#8211; <strong>application</strong> &#038; <strong>presentation</strong>.  The only job for the presentation layer is to format the data into the HTML and send it to the browser.  Everything else falls to the application layer.</p>
<h3>Bad Example</h3>
<p>I decided to write a script that would utilize a database table in my sample database.  This example uses data from the article on how to <a href="http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/">Locate the Nearest Radar Station and Display Radar Images</a>.  This script will take your IP&#8217;s location, and show the 10 closest radar stations to that location &#8211; but displaying the results in way that should make you cringe.</p>
<p style="text-align: right; "><a href="/samples/414/fail.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;IP Geolocation Example&lt;/title&gt;
&lt;meta name=&quot;generator&quot; content=&quot;Bluefish 1.0.7&quot;&gt;
&lt;meta name=&quot;author&quot; content=&quot;Andrew Wells&quot;&gt;
&lt;meta name=&quot;date&quot; content=&quot;2008-12-26T17:05:21-0600&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;application/xhtml+xml; charset=UTF-8&quot;&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;?php
/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

echo '&lt;h2&gt;Details on IP Location:&lt;/h2&gt;';
echo '&lt;b&gt;Location ID:&lt;/b&gt; ' . $location['locId'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Country:&lt;/b&gt; ' . $location['country'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Region:&lt;/b&gt; ' . $location['region'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;City:&lt;/b&gt; ' . $location['city'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Postal Code:&lt;/b&gt; ' . $location['postalCode'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Latitude:&lt;/b&gt; ' . $location['latitude'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Longitude:&lt;/b&gt; ' . $location['longitude'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Metro Code:&lt;/b&gt; ' . $location['metroCode'] . &quot;&lt;br /&gt;\n&quot;;
echo '&lt;b&gt;Area Code:&lt;/b&gt; ' . $location['areaCode'] . &quot;&lt;br /&gt;\n&quot;;

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 10&quot;;
$result = mysql_query($query, $db) or die(mysql_error());

echo'&lt;h2&gt;Radar Site Details&lt;/h2&gt;&lt;table width=&quot;800&quot;&gt;';
echo '&lt;tr&gt;';
echo '&lt;th&gt;Station ID&lt;/th&gt;';
echo '&lt;th&gt;Lat&lt;/th&gt;';
echo '&lt;th&gt;Lon&lt;/th&gt;';
echo '&lt;th&gt;Updated&lt;/th&gt;';
echo '&lt;th&gt;Distance&lt;/th&gt;';
echo '&lt;/tr&gt;';
for ($i = 0, $n = mysql_num_rows($result); $i &lt; $n; $i++)
{
	$radar = mysql_fetch_assoc($result);
	echo '&lt;tr&gt;';
	echo '&lt;td&gt;' . $radar['id'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['lat'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['lon'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['updated'] . '&lt;/td&gt;';
	echo '&lt;td&gt;' . $radar['distance'] . '&lt;/td&gt;';
	echo '&lt;/tr&gt;';
}
echo '&lt;/table&gt;';
?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This isn&#8217;t a worst cast scenario &#8211; I&#8217;ve seen worse, but I would like to point out the PHP code block in the middle of the header and footer HTML.  Notice all the application work I&#8217;m doing in lines 13-67 that is right in the middle of the HTML output.  Looking further, you can see that I am using echo statements to output the table HTML and other code.  This is <strong>bad</strong>.  It makes it hard to change the HTML without messing with the PHP, and it makes it next to impossible for a designer to work with it.</p>
<h3>Good Example</h3>
<p>Here is a better example with most of the logic separated from the HTML.</p>
<p style="text-align: right; "><a href="/samples/414/win.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php
/* replace with your own DB connection code */
require('../includes/database.php');
$db = db_connect();

/* get the IP address and make sure it is an unsigned integer */
$ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR']));

/* fetch the location id */
$query = &quot;SELECT locId FROM CityBlocks WHERE $ip BETWEEN startIpNum AND endIpNum LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$row = mysql_fetch_assoc($result);

/* now fetch the location */
$locId = $row['locId'];
$query = &quot;SELECT * FROM CityLocation WHERE locId = $locId LIMIT 1&quot;;
$result = mysql_query($query, $db) or die(mysql_error());
$location = mysql_fetch_assoc($result);

/* offset the coordinates by 3, and find the closest station */
$lat = $location['latitude'] + 3;
$lon = $location['longitude'] - 3;
$query = &quot;SELECT *, SQRT(POW(69.1 * (lat - $lat), 2) + 
			POW(69.1 * ($lon - lon) * COS(lat / 57.3 ), 2 )) AS distance 
			FROM RadarSites ORDER BY distance ASC LIMIT 10&quot;;
$result = mysql_query($query, $db) or die(mysql_error());

for ($i = 0, $n = mysql_num_rows($result); $i &lt; $n; $i++)
{
	$radars[] = mysql_fetch_assoc($result);
}
?&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;IP Geolocation Example&lt;/title&gt;
&lt;meta name=&quot;generator&quot; content=&quot;Bluefish 1.0.7&quot;&gt;
&lt;meta name=&quot;author&quot; content=&quot;Andrew Wells&quot;&gt;
&lt;meta name=&quot;date&quot; content=&quot;2008-12-26T17:05:21-0600&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;meta http-equiv=&quot;content-type&quot; content=&quot;application/xhtml+xml; charset=UTF-8&quot;&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h2&gt;Details on IP Location:&lt;/h2&gt;
&lt;b&gt;Location ID:&lt;/b&gt; &lt;?=$location['locId']?&gt;&lt;br /&gt;
&lt;b&gt;Country:&lt;/b&gt; &lt;?=$location['country']?&gt;&lt;br /&gt;
&lt;b&gt;Region:&lt;/b&gt; &lt;?=$location['region']?&gt;&lt;br /&gt;
&lt;b&gt;City:&lt;/b&gt; &lt;?=$location['city']?&gt;&lt;br /&gt;
&lt;b&gt;Postal Code:&lt;/b&gt; &lt;?=$location['postalCode']?&gt;&lt;br /&gt;
&lt;b&gt;Latitude:&lt;/b&gt; &lt;?=$location['latitude']?&gt;&lt;br /&gt;
&lt;b&gt;Longitude:&lt;/b&gt; &lt;?=$location['longitude']?&gt;&lt;br /&gt;
&lt;b&gt;Metro Code:&lt;/b&gt; &lt;?=$location['metroCode']?&gt;&lt;br /&gt;
&lt;b&gt;Area Code:&lt;/b&gt; &lt;?=$location['areaCode']?&gt;&lt;br /&gt;

&lt;h2&gt;Radar Site Details&lt;/h2&gt;&lt;table width=&quot;800&quot;&gt;
&lt;tr&gt;
	&lt;th&gt;Station ID&lt;/th&gt;
	&lt;th&gt;Lat&lt;/th&gt;
	&lt;th&gt;Lon&lt;/th&gt;
	&lt;th&gt;Updated&lt;/th&gt;
	&lt;th&gt;Distance&lt;/th&gt;
&lt;/tr&gt;
&lt;?php foreach ($radars as $radar): ?&gt;
&lt;tr&gt;
	&lt;td&gt;&lt;?=$radar['id']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['lat']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['lon']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['updated']?&gt;&lt;/td&gt;
	&lt;td&gt;&lt;?=$radar['distance']?&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;?php endforeach; ?&gt;

&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In lines 46-54, I am using PHP shorthand tags to output PHP variables in a cleaner way.  The other thing you will notice is that there is no getting around the loop structure that is needed to output the 10 radar sites.  We can do it without the curly braces though, and with neater &#8220;tags&#8221; in the HTML to control the loop.</p>
<p>Another thing to mention &#8211; I would even have the PHP block in a different file, but I combined them for the simplicity of the example.</p>
<h3>PHP Shorthand Tags and Alternative Syntax</h3>
<p>Since the presentation files are to be more focused on the HTML, and won&#8217;t be very PHP-intense, we can use simplified tags.  To output PHP variables in HTML without the PHP opening/closing tags, we use the shorthand method:</p>
<pre class="brush: php">
&lt;!-- old method --&gt;
&lt;html&gt;
&lt;?php
    echo $some_var;
?&gt;
&lt;/html&gt;

&lt;!-- better method --&gt;
&lt;html&gt;
&lt;?=$some_var?&gt;
&lt;/html&gt;
</pre>
<p>If we need to have a control structure, such as an if statement or loop, we do it this way:</p>
<pre class="brush: php">
&lt;html&gt;
&lt;?php if ($condition): ?&gt;
&lt;p&gt;Some content here&lt;/p&gt;
&lt;?php endif; ?&gt;
&lt;/html&gt;
</pre>
<p>Here is a loop example:</p>
<pre class="brush: php">
&lt;html&gt;
&lt;?php for ($i = 0; $i &lt; 10; $i++): ?&gt;
&lt;p&gt;Some content here with the current index of &lt;?=$i?&gt;&lt;/p&gt;
&lt;?php endfor; ?&gt;
&lt;/html&gt;
</pre>
<p>So there you have it &#8211; a few tips for you to create more readable code.  I have read that doing it this way with several PHP opening/closing tags can hurt performance by a hair, but I prefer losing a few CPU cycles over several hours debugging later down the road.  The choice is yours. <img src='http://phpstarter.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Examples with Parsing NDFD Data in PHP</title>
		<link>http://phpstarter.net/2009/03/more-examples-with-parsing-ndfd-data-in-php/</link>
		<comments>http://phpstarter.net/2009/03/more-examples-with-parsing-ndfd-data-in-php/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 11:00:10 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Weather]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=396</guid>
		<description><![CDATA[I covered how to Parse Weather Forecast Data (from the NDFD) in PHP in a previous article, but due to the amount of questions I received, I decided to show some more usage techniques and examples. In this article, I will cover the time-series option as well as some methods on how to make some [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>I covered how to <a href="http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/">Parse Weather Forecast Data (from the NDFD) in PHP</a> in a previous article, but due to the amount of questions I received, I decided to show some more usage techniques and examples.  In this article, I will cover the time-series option as well as some methods on how to make some data more presentable.</p>
<p><span id="more-396"></span></p>
<h3>Fetching Time-Series Data from the NDFD</h3>
<p><em>This was covered as an appendix in the previous article, but I will include it here as well in case you are only reading it in the feeds or by email.</em></p>
<p>Requesting the time-series data returns a whole bunch more information. As requested, here is an example on how to fetch it. Change the desired parameters to ‘true’. The other examples on how to parse the time layouts and formatting data works on this XML, too.</p>
<p style="text-align: right; "><a href="/samples/396/ndfd_timeseries.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php

/* http://sourceforge.net/projects/nusoap/ */
require('../includes/nusoap/nusoap.php');

$parameters = array('product'	=&gt; 'time-series',
					'latitude'  =&gt; 41.879535,
					'longitude'	=&gt; -87.624333,
					'weatherParameters' =&gt; array(
					
	'maxt' =&gt; true,			'mint' =&gt; false,		'temp' =&gt; false,			'dew' =&gt; false,	
	'appt' =&gt; true,			'pop12' =&gt; false,		'qpf' =&gt; false,				'snow' =&gt; false,	
	'sky' =&gt; false,			'rh' =&gt; false,			'wspd' =&gt; false,			'wdir' =&gt; false,	
	'wx' =&gt; false,			'icons' =&gt; false,		'waveh' =&gt; false,			'incw34' =&gt; false,	
	'incw50' =&gt; false,		'incw64' =&gt; false,		'cumw34' =&gt; false,			'cumw50' =&gt; false,	
	'cumw64' =&gt; false,		'wgust' =&gt; false,		'conhazo' =&gt; false,			'ptornado' =&gt; false,	
	'phail' =&gt; false,		'ptstmwinds' =&gt; false,	'pxtornado' =&gt; false,		'pxhail' =&gt; false,	
	'pxtstmwinds' =&gt; false,	'ptotsvrtstm' =&gt; false,	'pxtotsvrtstm' =&gt; false,	'tmpabv14d' =&gt; false,	
	'tmpblw14d' =&gt; false,	'tmpabv30d' =&gt; false,	'tmpblw30d' =&gt; false,		'tmpabv90d' =&gt; false,	
	'tmpblw90d' =&gt; false,	'prcpabv14d' =&gt; false,	'prcpblw14d' =&gt; false,		'prcpabv30d' =&gt; false,	
	'prcpblw30d' =&gt; false,	'prcpabv90d' =&gt; false,	'prcpblw90d' =&gt; false,		'precipa_r' =&gt; false,	
	'sky_r' =&gt; false,		'td_r' =&gt; false,		'temp_r' =&gt; false,			'wdir_r' =&gt; false,	
	'wwa' =&gt; false,			'wspd_r' =&gt; false)
	
					);

try
{
	/* create the nuSOAP object */
	$c = new nusoap_client('http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl', 'wsdl');
	
	/* make the request */
	$result = $c-&gt;call('NDFDgen', $parameters);
}
catch (Exception $ex)
{
	/* nuSOAP throws an exception is there was a problem fetching the data */
	echo 'failed';
}

header('Content-type: text/xml');
echo $result;

/* ?&gt; */
</pre>
<h3>Merging Sets of Data with Different Time Layouts</h3>
<p>The different sets of data in the NDFD are most likely going to be wanted to be displayed together.  For example, on <a href="http://chasingweather.com/forecast/lat_lon/41.3969/-87.3274#area-forecast">this page</a>, you will see that I have the conditions icons, max temps, and min temps all showing at the same time intervals.  But how is that possible?</p>
<p>In this example case, we are going to match up the high temperatures with their conditions icon.  This may not give an accurate weather condition for the day because we are going to pick the icon that is the closest to the time stamp given for that temperature.  In other words, the condition icons are for every hour or so, and the temperatures are only twice a day.  We have to pick two of those icons to match up with the two temperatures.  So for example, if the forecast for the day is &#8220;sunny in the morning, then t&#8217;storms in the afternoon&#8221;, the icon will show up as sunny.</p>
<p style="text-align: right; "><a href="/samples/396/con_times.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php

/* returns the next element based on the key provided */
function array_next($array, $key, $offset = 0)
{
	/* if the key exists, we're done */
	if (isset($array[$key]) &amp;&amp; $offset == 0) return $array[$key];
	
	/* insert the key into the array and sort it */
	$array[$key] = 1;
	ksort($array);
	
	/* now get the array in order */
	$keys = array_keys($array);
	
	/* find where our inserted key is and get the next element */
	$index = array_search($key, $keys);
	if ($offset == 0) $offset = 1;
	$index += $offset;
	return (isset($keys[$index])) ? $array[$keys[$index]] : FALSE;
}

/**
 * load the forecast data array as produced in the below example:
 * http://phpstarter.net/samples/348/parse_data.php
 * More information:
 * http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/
 */
include('parse_data.php');
$forecast = parse_data();

?&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;NDFD Usage Example w/ Different Time Layouts&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Show High Temps with Icons&lt;/h1&gt;
&lt;?php foreach ($forecast['max_temps'] as $timestamp =&gt; $temp): ?&gt;
&lt;p&gt;&lt;?=$field?&gt;&lt;br /&gt;
&lt;img src=&quot;&lt;?=array_next($forecast['icons'], $timestamp)?&gt;&quot; /&gt;&lt;br /&gt;
High: &lt;?=$temp?&gt;&lt;/p&gt;
&lt;?php endforeach; ?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In the above example, the array_next() function is the one that allows us to match up the data arrays.  The first parameter is the array of the weather data that we are trying to find&#8230;or in our case, the conditions icon.  The second parameter is the key that we want to get close to&#8230;or in our case, the timestamp for the temperature we are displaying.  So, we loop through the temperatures and search for the closest icon for each one.</p>
<h3>Collecting and Using the Time Labels</h3>
<p>Depending on that kind of data you are requesting, some of the time layouts contain the time labels.  I had those time labels displayed in a data array called time_labels in a <a target="_blank" href="http://phpstarter.net/samples/348/parse_data.php">previous example</a>, but I didn&#8217;t explain how I did it.  Basically, I wrote a function that sifts through all of the time layouts.  If it finds one with a &#8220;period-name&#8221; attribute, it saves that timestamp and the period name in a data array similar to the other data items (temp, conditions, etc).</p>
<p style="text-align: right; "><a href="/samples/396/time_labels.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php

/**
 * get the time layouts in an array form
 * 
 * @param string $xml
 * @return mixed
 */
function get_time_labels($xml)
{
	$data = $xml-&gt;xpath(&quot;//start-valid-time&quot;);
	$times = array();
	
	foreach ($data as $field =&gt; $value)
	{
		if ((string)$value['period-name'])
		{
			$index = (string)$value;
			$times[$index] = (string)$value['period-name'];
		}
	}
	
	ksort($times);
	
	return $times;
}

/* working with stale data, but why query for it every time */
$xml = file_get_contents('ndfd_forecast.xml');
$xml = new SimpleXMLElement($xml);

$time_labels = get_time_labels($xml);

header('Content-type: text/plain');
var_dump($time_labels);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>We can apply it with the Merging Sets of Data example, and end up with something like this:</p>
<p style="text-align: right; "><a href="/samples/396/labels_conditions.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php

/* returns the next element based on the key provided */
function array_next($array, $key, $offset = 0)
{
	/* if the key exists, we're done */
	if (isset($array[$key]) &amp;&amp; $offset == 0) return $array[$key];
	
	/* insert the key into the array and sort it */
	$array[$key] = 1;
	ksort($array);
	
	/* now get the array in order */
	$keys = array_keys($array);
	
	/* find where our inserted key is and get the next element */
	$index = array_search($key, $keys);
	if ($offset == 0) $offset = 1;
	$index += $offset;
	return (isset($keys[$index])) ? $array[$keys[$index]] : FALSE;
}

/**
 * load the forecast data array as produced in the below example:
 * http://phpstarter.net/samples/348/parse_data.php
 * More information:
 * http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/
 */
include('parse_data.php');
$forecast = parse_data();

?&gt;
&lt;html&gt;
&lt;head&gt;&lt;title&gt;Show Condition Icons with Time Labels&lt;/title&gt;&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Show Condition Icons with Time Labels&lt;/h1&gt;
&lt;?php foreach ($forecast['time_labels'] as $timestamp =&gt; $label): ?&gt;
&lt;p&gt;&lt;?=$label?&gt;&lt;br /&gt;
&lt;img src=&quot;&lt;?=array_next($forecast['icons'], $timestamp)?&gt;&quot; /&gt;&lt;/p&gt;
&lt;?php endforeach; ?&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>So there you have it &#8211; more possible applications and examples with this abundant weather forecast data.  As with all other advanced articles on phpstarter.net, this is not intended provide you with copy-and-paste code to paste right in your web applications with little or no modifications.  You really need to understand how this all works, and adapt it as necessary or rewrite the examples completely based on what you learned here and what you need to use it for.  The point is to get you to understand the concepts used here so you can <strong>apply</strong> them to your web applications.  Happy coding! <img src='http://phpstarter.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/03/more-examples-with-parsing-ndfd-data-in-php/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Parse Current Weather Conditions Data from the NWS in PHP</title>
		<link>http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/</link>
		<comments>http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 12:00:36 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Weather]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=386</guid>
		<description><![CDATA[In a previous article, I covered 5 Sources of Free Weather Data for your Site, but did not provide any actual code to use the data. Last week, I covered source #1 and showed how to Parse Weather Forecast Data (from the NDFD) in PHP. For this article, I will show how to parse source [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>In a previous article, I covered <a href="http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/">5 Sources of Free Weather Data for your Site</a>, but did not provide any actual code to use the data.  Last week, I covered source #1 and showed how to <a href="http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/">Parse Weather Forecast Data (from the NDFD) in PHP</a>.  For this article, I will show how to parse source #2 &#8211; the current weather conditions data as provided by the National Weather Service.</p>
<p><span id="more-386"></span></p>
<h3>Fetching the Data for One Station at a Time</h3>
<p>This is ideal for a website that wants to show the current conditions for one location.  Go to the <a href="http://www.weather.gov/xml/current_obs/">XML Feeds</a> page, and find your station.  We need to know the station id for your area, so select your state, and then find the closest station to you.</p>
<p>The example below shows how easy it is to fetch the XML and format it into something we can read.</p>
<pre name="code" class="brush: php:collapse">&lt;?php

/**
 * Download a copy here:
 * http://sourceforge.net/projects/snoopy/
 */
require('../includes/Snoopy.class.php');

/**
 * Load a single station and return the data
 */
function load_single_station($station_id, &amp;$xml)
{
	$snoopy= new Snoopy();
	$snoopy-&gt;fetch('http://www.weather.gov/xml/current_obs/' . $station_id . '.xml', $xml_tmp . $station_id . '.xml');
	
	if (!$snoopy-&gt;results)
	{
		/* oops */
		return false;
	}
	
	$data = $snoopy-&gt;results;
	
	try
	{
		/* convert the XML into a data object */
		$xml = @new SimpleXMLElement($data);
		/* convert that data object into an array, and return it */
		return get_object_vars($xml);
	}
	catch (Exception $e)
	{
		/* we got an empty or invalid XML file */
		return false;
	}
}

$conditions = load_single_station('KLOT', $xml);
var_dump($conditions);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>Although that example gets the job done, we are going to want to do some caching.  It&#8217;s a bit pointless to be fetching that XML file every time a page is requested.  With a little bit of database code, we can make it relatively easy.  First, setup a database that your script has access to, and create this table:</p>
<pre class="brush: sql">
CREATE TABLE `Current` (
  `suggested_pickup` varchar(55) NOT NULL,
  `last_update` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `suggested_pickup_period` smallint(6) NOT NULL,
  `location` varchar(55) NOT NULL,
  `station_id` varchar(10) NOT NULL,
  `latitude` decimal(5,2) NOT NULL,
  `longitude` decimal(5,2) NOT NULL,
  `observation_time` varchar(255) NOT NULL,
  `observation_time_rfc822` varchar(255) NOT NULL,
  `weather` varchar(55) NOT NULL,
  `temperature_string` varchar(55) NOT NULL,
  `temp_f` smallint(6) NOT NULL,
  `temp_c` smallint(6) NOT NULL,
  `relative_humidity` tinyint(4) NOT NULL,
  `wind_string` varchar(55) NOT NULL,
  `wind_dir` varchar(55) NOT NULL,
  `wind_degrees` smallint(6) NOT NULL,
  `wind_mph` smallint(6) NOT NULL,
  `wind_gust_mph` smallint(6) NOT NULL,
  `pressure_string` varchar(55) NOT NULL,
  `pressure_mb` smallint(6) NOT NULL,
  `pressure_in` decimal(5,2) NOT NULL,
  `dewpoint_string` varchar(55) NOT NULL,
  `dewpoint_f` smallint(6) NOT NULL,
  `dewpoint_c` smallint(6) NOT NULL,
  `heat_index_string` varchar(55) NOT NULL,
  `heat_index_f` smallint(6) NOT NULL,
  `heat_index_c` smallint(6) NOT NULL,
  `windchill_string` varchar(55) NOT NULL,
  `windchill_f` smallint(6) NOT NULL,
  `windchill_c` smallint(6) NOT NULL,
  `visibility_mi` decimal(5,2) NOT NULL,
  `icon_url_base` varchar(255) NOT NULL,
  `icon_url_name` varchar(55) NOT NULL,
  `two_day_history_url` varchar(255) NOT NULL,
  `ob_url` varchar(255) NOT NULL,
  PRIMARY KEY  (`station_id`),
  KEY `latitude` (`latitude`,`longitude`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
</pre>
<p>After that MySQL table is created, have a look at this next example.  It&#8217;s the same as the last one, but with two new functions: load_single_station_cache() &#038; save_conditions().  The load_single_station_cache() function checks the table for a non-stale record for the specified station.  If it finds one, it returns that database record, and no XML file is downloaded.  If it doesn&#8217;t find one, it calls up load_single_station(), just like the first example, and then saves that data with the save_conditions() function.</p>
<p style="text-align: right; "><a href="/samples/386/single_station_cache.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php

/**
 * Download a copy here:
 * http://sourceforge.net/projects/snoopy/
 */
require('../includes/Snoopy.class.php');

/**
 * replace with your database connection code
 */
require('../includes/database.php');
db_connect();

/**
 * Load a single station and return the data
 */
function load_single_station($station_id, &amp;$xml)
{
	$snoopy= new Snoopy();
	$snoopy-&gt;fetch('http://www.weather.gov/xml/current_obs/' . $station_id . '.xml', $xml_tmp . $station_id . '.xml');
	
	if (!$snoopy-&gt;results)
	{
		/* oops */
		return false;
	}
	
	$data = $snoopy-&gt;results;
	
	try
	{
		/* convert the XML into a data object */
		$xml = @new SimpleXMLElement($data);
		/* convert that data object into an array, and return it */
		return get_object_vars($xml);
	}
	catch (Exception $e)
	{
		/* we got an empty or invalid XML file */
		return false;
	}
}

/**
 * Save the weather conditions to the database table.
 */
function save_conditions($conditions)
{
	/**
	 * Get the columns and interect that list with the data array, 
	 * so we don't try to insert some fields that don't exist
	 */
	$query = &quot;SHOW COLUMNS FROM Current&quot;;
	$result = mysql_query($query);
	$fields = array();
	
	for ($i = 0, $n = mysql_num_rows($result); $i &lt; $n; $i++)
	{
		$row = mysql_fetch_row($result);
		$fields[] = $row[0];
	}
	$fields = array_flip($fields);
	$conditions = array_intersect_key($conditions, $fields);
	
	/**
	 * Form the data pairs into query format.
	 * Uncomment the echo statement below to see what it's doing.
	 */
	$fields = $values = '';
	foreach ($conditions as $field =&gt; $value)
	{
		$fields .= $field . &quot;,&quot;;
		$values .= &quot;'&quot; . mysql_real_escape_string($value) . &quot;',&quot;;
	}

	/* remove the last comma from both variables */
	$fields = substr($fields, 0, strlen($fields) - 1);
	$values = substr($values, 0, strlen($values) - 1);
	
	$query = &quot;DELETE FROM Current WHERE station_id = '{$conditions['station_id']}' LIMIT 1&quot;;
	mysql_query($query);
	$query = &quot;INSERT INTO Current ($fields) VALUES ($values)&quot;;
	//echo $query;
	$result = mysql_query($query);
	if (!$result) die(mysql_error());
}

/**
 * Load the weather conditions from the DB table, and make the necessary 
 * calls if a recent record does not exist.
 */
function load_single_station_cache($station_id, &amp;$xml)
{
	$station_id_esc = mysql_real_escape_string($station_id);
	
	/* no results will be returned if there is no record, *or* if 
		the record is more than 5400 seconds (90 minutes) old */
	$query = &quot;SELECT * FROM Current WHERE station_id = '$station_id_esc' &amp;&amp; last_update + 5400 &gt; NOW() LIMIT 1&quot;;
	$result = mysql_query($query);
	if (!$result) die(mysql_error());
	
	if (mysql_num_rows($result) == 0)
	{
		/* load a fresh set of conditions */
		$conditions = load_single_station($station_id, &amp;$xml);
		
		/* don't forget to save it for later */
		save_conditions($conditions);
		
		return $conditions;
	}
	else
	{
		/* we got it */
		return mysql_fetch_assoc($result);
	}
}

$conditions = load_single_station_cache('KLOT', $xml);
header('Content-type: text/plain');
var_dump($conditions);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<h3>Fetching the Data for all Stations</h3>
<p>Higher traffic sites that show conditions for all or most of the available stations may want to download all of the stations at once from their <a href="http://www.weather.gov/xml/current_obs/">data feeds page</a>, and import them into a database.  To do this, we are going to need to download the zip file from the website, and then extract it.  I am not going to provide specific code, because it&#8217;s unique to the server environment.  Binary files can be downloaded via <a href="http://us.php.net/manual/en/book.curl.php">cURL</a> or <a href="http://us.php.net/manual/en/function.fsockopen.php">fsockopen()</a> as an alternative.  Once downloaded, use PHP&#8217;s <a href="http://us2.php.net/zip">Zip functions</a> to extract the files to a temp directory.  <a href="http://www.zlib.net/">Zlib</a> is required to open a zip archive in PHP, so if you don&#8217;t have it, you can use the <a href="http://us.php.net/manual/en/function.shell-exec.php">shell_exec()</a> function to run the necessary unzip functions in the shell, assuming that your server supports it.</p>
<p>Once you have the XML files at your disposal, use something like the <a href="http://us2.php.net/manual/en/function.scandir.php">scandir()</a> function and import all files using something like the single-station example.</p>
<p>So there you have it &#8211; XML files turned into an easy to manage, cache-able associative array.</p>
<div class="m_info">If these examples were enough to make your head spin, there are easy alternatives to show current conditions on your website.  Check out these <a href="http://wiki.wunderground.com/index.php/Weather_Stickers">free weather stickers</a> that are easier to use, although not as customizable.</div>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Parse Weather Forecast Data (from the NDFD) in PHP</title>
		<link>http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/</link>
		<comments>http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 12:00:44 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Advanced]]></category>
		<category><![CDATA[Weather]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=348</guid>
		<description><![CDATA[In a previous article, I covered 5 Sources of Free Weather Data for your Site, but did not provide any actual code to use the data. Starting with this article, I will post instructions on how to handle this data as well as sample code. For this article, we will start with the National Digital [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>In a previous article, I covered <a href="http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/">5 Sources of Free Weather Data for your Site</a>, but did not provide any actual code to use the data.  Starting with this article, I will post instructions on how to handle this data as well as sample code.  For this article, we will start with the National Digital Forecast Database (NDFD) Simple Object Access Protocol (SOAP) Web Service.</p>
<p><span id="more-348"></span></p>
<h3>Where to Find the Data</h3>
<p>See <a href="http://www.weather.gov/xml">weather.gov/xml</a> for full details and available data.  We will be using the 24 Hourly format, which gives us temperatures, cloud cover %, weather type (rain, snow, etc), hazardous conditions, and even weather icons.</p>
<h3>Code to Fetch the Data</h3>
<p>Below is some sample code that will fetch the data.  The lat/lon coordinates need to be changed for your desired location on lines 10-11.  Currently, it is set for Chicago, IL.</p>
<pre name="code" class="brush: php">&lt;?php

/* http://sourceforge.net/projects/nusoap/ */
require('../includes/nusoap/nusoap.php');

$parameters = array('product'	=&gt; 'glance',
					'numDays'   =&gt; 5,
					'format'    =&gt; '24 hourly',
					'latitude'  =&gt; 41.879535,
					'longitude'	=&gt; -87.624333);

try
{
	/* create the nuSOAP object */
	$c = new nusoap_client('http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl', 'wsdl');
	
	/* make the request */
	$result = $c-&gt;call('NDFDgen', $parameters);
}
catch (Exception $ex)
{
	/* nuSOAP throws an exception is there was a problem fetching the data */
	echo 'failed';
}

header('Content-type: text/xml');
echo $result;

/* ?&gt; */
</pre>
<p>This is by no means a production sample.  You are going to want to cache the results somehow so you aren&#8217;t querying the NDFD every time you need this information.  It is only updated every hour at most, so there is no need to query it more frequent than that.</p>
<h3>Understanding the XML Output</h3>
<p>It took me a great deal of staring and reading to figure out how this XML output is organized.  Have a look at this <a href="/samples/348/ndfd_forecast.xml" target="_blank">sample output</a>, as I will refer to this specific example to explain the sections.  I recommend loading the sample XML file in Firefox or any other web browser that allows you to collapse and expand the XML tree.</p>
<p>First, collapse the &#8220;head&#8221; area by clicking on the minus next to the &#8220;head&#8221; tag.  Everything in there is pretty self-explanatory.  Our focus is going to be in the &#8220;data&#8221; tag.  Next, collapse all tags inside the &#8220;data&#8221; tag, except for the &#8220;parameters&#8221; tag, but collapse everything inside the &#8220;parameters&#8221; tag so we can see everything in there w/o scrolling.  Here is what your view should look like:</p>
<p><a href="http://phpstarter.net/wp-content/uploads/2009/02/ndfd_01.png"><img src="http://phpstarter.net/wp-content/uploads/2009/02/ndfd_01-590x261.png" alt="ndfd_01" title="ndfd_01" width="590" height="261" class="alignnone size-large wp-image-352" /></a></p>
<p>Now we are at a point where we can see how this is all grouped together.  As we can see, the &#8220;parameters&#8221; section shows the products that are available, which are temperature (minimum), temperature (maximum), cloud-amount, weather, conditions-icon, and hazards.  Each of them is associated with a time layout because most products are on a different time scale.  For example, max temps are during the afternoon &#038; once a day, min temps are at night &#038; once a day, the conditions icons are at several points throughout the next several days, etc.  It is separated out this way because not all products have a different time scale &#8211; some are the same, like &#8220;weather&#8221; and &#8220;conditions-icon&#8221; in our example.</p>
<p>Time to match each product to their time layout.  We see that the maximum temps have the time layout of &#8220;k-p24h-n7-1&#8243;, so we go up to the time layouts and find one with the layout-key of &#8220;k-p24h-n7-1&#8243;.</p>
<p><a href="http://phpstarter.net/wp-content/uploads/2009/02/ndfd_02.png"><img src="http://phpstarter.net/wp-content/uploads/2009/02/ndfd_02-590x418.png" alt="ndfd_02" title="ndfd_02" width="590" height="418" class="alignnone size-large wp-image-354" /></a></p>
<p>We have to code a way to merge all data sets with their corresponding time layout.  This may look complicated, but I will show you a somewhat easy way to parse this in PHP.</p>
<p style="text-align: right; "><a href="/samples/348/parse_times.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php
/************************************/
/* some functions we will use later */
/************************************/

/**
 * get the string values of the object items
 * @param mixed $object the XML object to extract the string values from
 * @return array
 */
function get_values($object)
{
	$arr = array();
	foreach ($object as $field =&gt; $value)
	{
		$arr[] = (string)$value;
	}
	
	return $arr;
}

/*****************************/
/* actual script starts here */
/*****************************/

/* load our example from http://phpstarter.net/samples/348/ndfd_forecast.xml */
$xml_data = file_get_contents('ndfd_forecast.xml');

/* parse the XML data into a giant data object */
try
{
	$xml = new SimpleXMLElement($xml_data);
}
catch (Exception $ex)
{
	/* the XML was probably invalid */
	die('Failed to parse the XML');
}

/* all time layouts go in here with the layout-key as the array keys */
$times = array();

/* loop through the time-layouts in the XML */
foreach ($xml-&gt;xpath('//time-layout') as $field =&gt; $value)
{
	/* get the layout-key to make it the array key value */
	$layout = (string)$value-&gt;{'layout-key'};
	
	
	$times[$layout] = array('start' =&gt; get_values($value-&gt;xpath('start-valid-time')), 
							'end' =&gt; get_values($value-&gt;xpath('end-valid-time')));
}

header('Content-type: text/plain');
var_dump($times);


/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>Now we have all the time layouts in a way we can manage it.  The next task is to match it up to the data to their respective time layouts.  This next example includes the code to organize the time layouts, and then organize the data to correspond with the times.  Running the example below will show that the data is now neatly organized in a way that it can be easily used.</p>
<p style="text-align: right; "><a href="/samples/348/parse_data.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php
/************************************/
/* some functions we will use later */
/************************************/

/**
 * get the string values of the object items
 * @param mixed $object the XML object to extract the string values from
 * @return array
 */
function get_values($object)
{
	$arr = array();
	foreach ($object as $field =&gt; $value)
	{
		$arr[] = (string)$value;
	}
	
	return $arr;
}

/**
 * Combine a time layout with a product
 * 
 * @param string $data_xpath the xpath to the data set
 * @param string $time_xpath the xpath to the time layout
 * @param array $times the big assoc array of all the time layouts
 */
function merge_times_data($data_xpath, $time_xpath, $times, $xml)
{
	$data = get_values($xml-&gt;xpath($data_xpath));
	$time_layout = $xml-&gt;xpath($time_xpath);
	if (!$time_layout) return false;
	$time_layout = (string)$time_layout[0]['time-layout'];
	$data = array_combine($times[$time_layout]['start'], $data);
	
	return $data;
}

/**
 * get the time layouts in an array form
 * 
 * @param string $xml
 * @return mixed
 */
function get_time_labels($xml)
{
	$data = $xml-&gt;xpath(&quot;//start-valid-time&quot;);
	$times = array();
	
	foreach ($data as $field =&gt; $value)
	{
		if ((string)$value['period-name'])
		{
			$index = (string)$value;
			$times[$index] = (string)$value['period-name'];
		}
	}
	
	ksort($times);
	
	return $times;
}

/*****************************/
/* actual script starts here */
/*****************************/

/* load our example from http://phpstarter.net/samples/348/ndfd_forecast.xml */
$xml_data = file_get_contents('ndfd_forecast.xml');

/* parse the XML data into a giant data object */
try
{
	$xml = new SimpleXMLElement($xml_data);
}
catch (Exception $ex)
{
	/* the XML was probably invalid */
	die('Failed to parse the XML');
}

/* all time layouts go in here with the layout-key as the array keys */
$times = array();

/* loop through the time-layouts */
foreach ($xml-&gt;xpath('//time-layout') as $field =&gt; $value)
{
	/* get the layout-key to make it the array key value */
	$layout = (string)$value-&gt;{'layout-key'};
	
	
	$times[$layout] = array('start' =&gt; get_values($value-&gt;xpath('start-valid-time')), 
							'end' =&gt; get_values($value-&gt;xpath('end-valid-time')));
}

$forecast['max_temps'] = merge_times_data(&quot;//parameters/temperature[@type='maximum']/value&quot;, 
	&quot;//parameters/temperature[@type='maximum']&quot;, $times, $xml);
$forecast['min_temps'] = merge_times_data(&quot;//parameters/temperature[@type='minimum']/value&quot;, 
	&quot;//parameters/temperature[@type='minimum']&quot;, $times, $xml);
$forecast['temps'] = array_merge($forecast['min_temps'], $forecast['max_temps']);
$forecast['icons'] = merge_times_data(&quot;//parameters/conditions-icon/icon-link&quot;, 
	&quot;//parameters/conditions-icon&quot;, $times, $xml);
$forecast['time_labels'] = get_time_labels($xml);

header('Content-type: text/plain');
var_dump($forecast);

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>There is another function in that example that associates the times to the time labels that you see in the XML.  Some of them has a parameter called &#8220;period-name&#8221;, which is the day of the week or holiday name, if applicable.</p>
<h3>How to Use the Formatted Data</h3>
<p>For this last example, I will show you in the simplest terms how to use this data.  Remember, we are not pulling data from the NDFD live &#8211; this is using the XML from our <a href="/samples/348/ndfd_forecast.xml" target="_blank">earlier example</a>, so the temps are for mid-winter in NW Indiana.</p>
<p style="text-align: right; "><a href="/samples/348/ndfd_usage.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php:collapse">&lt;?php

/**
 * pick up where we left off from the last example
 * no need to generate the data array again here
 */
$forecast = file_get_contents('data.txt');
$forecast = unserialize($forecast);

/**
 * Show the temperatures
 */

foreach ($forecast['max_temps'] as $field =&gt; $value)
{
	echo 'High temp for ' . $forecast['time_labels'][$field] . ': ' . $value . &quot;&lt;br /&gt;\n&quot;;
}

foreach ($forecast['min_temps'] as $field =&gt; $value)
{
	echo 'Low temp for ' . $forecast['time_labels'][$field] . ': ' . $value . &quot;&lt;br /&gt;\n&quot;;
}

/**
 * Why do I comment out the PHP closing tag?
 * See: http://phpstarter.net/2009/01/omit-the-php-closing-tag/
 */
/* ?&gt; */
</pre>
<p>So there you have it &#8211; an XML parsing nightmare made easy.  This method is in my opinion the best way to receive and parse this data from the National Weather Service.  It may not be the best way for everyone, so if you have something better to add, please post a comment!</p>
<h3>(Added 2009/02/20) Fetching Time-Series Data from the NDFD</h3>
<p>Requesting the time-series data returns a whole bunch more information.  As requested, here is an example on how to fetch it.  Change the desired parameters to &#8216;true&#8217;.  The other examples on how to parse the time layouts and formatting data works on this XML, too.</p>
<pre name="code" class="brush: php:collapse">&lt;?php

/* http://sourceforge.net/projects/nusoap/ */
require('../includes/nusoap/nusoap.php');

$parameters = array('product'	=&gt; 'time-series',
					'latitude'  =&gt; 41.879535,
					'longitude'	=&gt; -87.624333,
					'weatherParameters' =&gt; array(
					
	'maxt' =&gt; true,			'mint' =&gt; false,		'temp' =&gt; false,			'dew' =&gt; false,	
	'appt' =&gt; true,			'pop12' =&gt; false,		'qpf' =&gt; false,				'snow' =&gt; false,	
	'sky' =&gt; false,			'rh' =&gt; false,			'wspd' =&gt; false,			'wdir' =&gt; false,	
	'wx' =&gt; false,			'icons' =&gt; false,		'waveh' =&gt; false,			'incw34' =&gt; false,	
	'incw50' =&gt; false,		'incw64' =&gt; false,		'cumw34' =&gt; false,			'cumw50' =&gt; false,	
	'cumw64' =&gt; false,		'wgust' =&gt; false,		'conhazo' =&gt; false,			'ptornado' =&gt; false,	
	'phail' =&gt; false,		'ptstmwinds' =&gt; false,	'pxtornado' =&gt; false,		'pxhail' =&gt; false,	
	'pxtstmwinds' =&gt; false,	'ptotsvrtstm' =&gt; false,	'pxtotsvrtstm' =&gt; false,	'tmpabv14d' =&gt; false,	
	'tmpblw14d' =&gt; false,	'tmpabv30d' =&gt; false,	'tmpblw30d' =&gt; false,		'tmpabv90d' =&gt; false,	
	'tmpblw90d' =&gt; false,	'prcpabv14d' =&gt; false,	'prcpblw14d' =&gt; false,		'prcpabv30d' =&gt; false,	
	'prcpblw30d' =&gt; false,	'prcpabv90d' =&gt; false,	'prcpblw90d' =&gt; false,		'precipa_r' =&gt; false,	
	'sky_r' =&gt; false,		'td_r' =&gt; false,		'temp_r' =&gt; false,			'wdir_r' =&gt; false,	
	'wwa' =&gt; false,			'wspd_r' =&gt; false)
	
					);

try
{
	/* create the nuSOAP object */
	$c = new nusoap_client('http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl', 'wsdl');
	
	/* make the request */
	$result = $c-&gt;call('NDFDgen', $parameters);
}
catch (Exception $ex)
{
	/* nuSOAP throws an exception is there was a problem fetching the data */
	echo 'failed';
}

header('Content-type: text/xml');
echo $result;

/* ?&gt; */
</pre>
<p>More tips can now be found here: <a href="http://phpstarter.net/2009/03/more-examples-with-parsing-ndfd-data-in-php/">More Examples with Parsing NDFD Data in PHP</a></p>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Create Dynamic Banner Ads for Blogs &amp; News Sites</title>
		<link>http://phpstarter.net/2009/02/create-dynamic-banner-ads-for-blogs-news-sites/</link>
		<comments>http://phpstarter.net/2009/02/create-dynamic-banner-ads-for-blogs-news-sites/#comments</comments>
		<pubDate>Thu, 12 Feb 2009 12:00:48 +0000</pubDate>
		<dc:creator>Andrew</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=248</guid>
		<description><![CDATA[When you visit a site, their usual advertisers might catch your eye once or twice, but after that, you forget it&#8217;s there. Designing a banner ad that automatically updates with information such as current sales or latest blog posts is a great way to get repeat clicks and return visitors. In this article, I&#8217;m going [...]
No related posts.]]></description>
			<content:encoded><![CDATA[<p>When you visit a site, their usual advertisers might catch your eye once or twice, but after that, you forget it&#8217;s there.  Designing a banner ad that automatically updates with information such as current sales or latest blog posts is a great way to get repeat clicks and return visitors.  In this article, I&#8217;m going to explain the code behind a dynamic ad implementation I use right here on this site.</p>
<p><span id="more-248"></span></p>
<p>If you go look at our <a href="/promote-this-site/">Promote this Site</a> page, you will see that a dynamic ad is offered that shows the most recent article on this site.  This is accomplished by creating a PHP script that reads this site&#8217;s <a href="/feed/">RSS Feed</a>, finding the latest post title, and overlaying it onto a graphic template.</p>
<p>I think this concept has potential with blogs and news sites because static banner ads become holes in the page to repeat visitors.  If I get somebody interested in this site once, then that banner will continue to catch their eyes when the article changes, and if they see a title that interests them again, they will visit the site again to read the latest article.</p>
<p>Here is some sample code based on what I have implemented on this site&#8217;s advertising page:</p>
<p style="text-align: right; "><a href="/samples/248/dyn_ad.php" target="_blank">Run This Example</a></p><pre name="code" class="brush: php">&lt;?php
	/* there is no need to call the feed up every time, so we will cache it for 1 hour */
	if (!file_exists('feed.cache') || filemtime('feed.cache') + 3600 &lt; time())
	{
		/**
		 * Looks like we don't have a recent copy, so we will use Snoopy to fetch the remote feed.
		 * See: http://phpstarter.net/2008/12/how-to-post-data-and-fetch-remote-pages-from-php-scripts/
		 */
		require('../includes/Snoopy.class.php');
		$snoopy = new Snoopy();
		
		/* set this to the RSS feed where we want to fetch the title from */
		$snoopy-&gt;fetch('http://phpstarter.net/feed/');
		
		/* save this to a local cache file so the RSS feed isn't called too often */
		file_put_contents('feed.cache', $snoopy-&gt;results);
	}
	
	/**
	 * We will use lastRSS to parse the feed.
	 * See: http://phpstarter.net/2009/01/load-rss-feeds-into-php-arrays-with-lastrss/
	 */
	require('../includes/lastRSS.php');
	$rss = new lastRss();
	
	/* load the cached file */
	$feed = $rss-&gt;get('feed.cache');
	
	/* this is the banner add that we will overlay the text on top of */
	$im = imagecreatefromgif('banner_ad_article.gif');
	
	/* set some colors */
	$black = imagecolorallocate($im, 0, 0, 0);
	$white = imagecolorallocate($im, 255, 255, 255);
	$orange = imagecolorallocate($im, 249, 160, 33);
	
	/* load the font we want to use */
	$f_domestic = '../includes/Domestic_Manners.ttf';
	
	/* this is the title taken from the RSS feed's first (or most recent) item */
	$title = $feed['items'][0]['title'];
	
	/* get the width of the to-be-printed text so we can center it */
	$bbox = imagettfbbox(12, 0, $f_domestic, $title);
	$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2);
	
	/* write the text to the base image */
	imagettftext($im, 12, 0, $x, 52, $orange, $f_domestic, $title);
	
	/* tell the browser that we are outputting a GIF image */
	header('Content-type: image/gif');
	
	/* render the image */
	imagegif($im);
?&gt;
</pre>
<p>No related posts.</p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/create-dynamic-banner-ads-for-blogs-news-sites/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

