<?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</title>
	<atom:link href="http://phpstarter.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://phpstarter.net</link>
	<description>PHP Tips &#38; Tools From Starters to Experts</description>
	<lastBuildDate>Wed, 29 Apr 2009 00:55:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<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 [...]


Related posts:<ul><li><a href='http://phpstarter.net/2009/01/load-rss-feeds-into-php-arrays-with-lastrss/' rel='bookmark' title='Permanent Link: Load RSS Feeds into PHP Arrays with lastRSS'>Load RSS Feeds into PHP Arrays with lastRSS</a></li><li><a href='http://phpstarter.net/2009/01/configuring-php-on-windows-systems/' rel='bookmark' title='Permanent Link: Configuring PHP on Windows Systems'>Configuring PHP on Windows Systems</a></li><li><a href='http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/' rel='bookmark' title='Permanent Link: Regular Expressions May Cause Irregularity'>Regular Expressions May Cause Irregularity</a></li></ul>]]></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>Related posts:<ul><li><a href='http://phpstarter.net/2009/01/load-rss-feeds-into-php-arrays-with-lastrss/' rel='bookmark' title='Permanent Link: Load RSS Feeds into PHP Arrays with lastRSS'>Load RSS Feeds into PHP Arrays with lastRSS</a></li><li><a href='http://phpstarter.net/2009/01/configuring-php-on-windows-systems/' rel='bookmark' title='Permanent Link: Configuring PHP on Windows Systems'>Configuring PHP on Windows Systems</a></li><li><a href='http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/' rel='bookmark' title='Permanent Link: Regular Expressions May Cause Irregularity'>Regular Expressions May Cause Irregularity</a></li></ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/04/loading-ini-files-in-php/feed/</wfw:commentRss>
		<slash:comments>0</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 [...]


Related posts:<ul><li><a href='http://phpstarter.net/2008/11/understanding-php-tags-code-blocks/' rel='bookmark' title='Permanent Link: Understanding PHP Tags &#038; Code Blocks'>Understanding PHP Tags &#038; Code Blocks</a></li><li><a href='http://phpstarter.net/2009/02/explosive-php-application/' rel='bookmark' title='Permanent Link: Explosive PHP Application'>Explosive PHP Application</a></li><li><a href='http://phpstarter.net/2009/01/omit-the-php-closing-tag/' rel='bookmark' title='Permanent Link: Omit the PHP Closing Tag'>Omit the PHP Closing Tag</a></li></ul>]]></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>Related posts:<ul><li><a href='http://phpstarter.net/2008/11/understanding-php-tags-code-blocks/' rel='bookmark' title='Permanent Link: Understanding PHP Tags &#038; Code Blocks'>Understanding PHP Tags &#038; Code Blocks</a></li><li><a href='http://phpstarter.net/2009/02/explosive-php-application/' rel='bookmark' title='Permanent Link: Explosive PHP Application'>Explosive PHP Application</a></li><li><a href='http://phpstarter.net/2009/01/omit-the-php-closing-tag/' rel='bookmark' title='Permanent Link: Omit the PHP Closing Tag'>Omit the PHP Closing Tag</a></li></ul></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>Working with AJAX</title>
		<link>http://phpstarter.net/2009/03/working-with-ajax/</link>
		<comments>http://phpstarter.net/2009/03/working-with-ajax/#comments</comments>
		<pubDate>Thu, 05 Mar 2009 06:00:24 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=409</guid>
		<description><![CDATA[AJAX is all over the internet today, and though completely unnecessary, a website with it can function much more quickly.  Data can be transferred to and from users efficiently, but a major drawback is the extra code needed and some security issues inherent.  Nevertheless, for certain applications, AJAX is great to know and [...]


Related posts:<ul><li><a href='http://phpstarter.net/2008/12/working-with-images-introducing-the-gd-library/' rel='bookmark' title='Permanent Link: Working with Images &#8211; Introducing the GD Library'>Working with Images &#8211; Introducing the GD Library</a></li><li><a href='http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/' rel='bookmark' title='Permanent Link: Dynamically Converting Text to an Image'>Dynamically Converting Text to an Image</a></li><li><a href='http://phpstarter.net/2008/12/run-codeigniter-from-the-command-line-ssh/' rel='bookmark' title='Permanent Link: Run CodeIgniter from the Command Line / SSH'>Run CodeIgniter from the Command Line / SSH</a></li></ul>]]></description>
			<content:encoded><![CDATA[<p>AJAX is all over the internet today, and though completely unnecessary, a website with it can function much more quickly.  Data can be transferred to and from users efficiently, but a major drawback is the extra code needed and some security issues inherent.  Nevertheless, for certain applications, AJAX is great to know and take your project to a new level.<span id="more-409"></span>The truth is that tutorials for learning the basics of AJAX are all over the internet.  For the quick setup of JavaScript, check out <a href="http://www.google.com/search?q=php+ajax+tutorial&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a" target="_blank">any of these</a>.  What I want to focus on are more practical applications of the PHP end of AJAX.  Surely you can understand the basics of passing variables to a PHP processing page, but let&#8217;s go over a few examples to understand what AJAX can accomplish for us.<br />
First of all, a soon-to-come feature on <a href="http://www.jeoreview.com">JeoReview</a> is on the page where boards can be created.  The issue is that there is a chance that someone will pick a board name that is already in use, and while the PHP is set up to catch the error, I would like for JavaScript to be able to handle it earlier and more quickly to prevent posting to pages over and over again.  So we will set up the JavaScript much like the examples show:</p>
<pre class="brush: javascript">
var xmlHttp;

function checkName(name) {
var url=&quot;checkName.php&quot;;
url=url+&quot;?n=&quot;+name;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open(&quot;GET&quot;,url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState==&quot;complete&quot;)
{
document.getElementById(&quot;nStatus&quot;).innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;);
}
catch (e)
{
xmlHttp=new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
}
}

return xmlHttp;
}</pre>
<p>I would place this into a separate JavaScript file and link it to the page where the action takes place, but all that is really needed from this point is to add an event trigger to the form field to execute this function.  Something like this:</p>
<pre class="brush: php">

...

&lt;input type=&#039;text&#039; value=&#039;&#039; onchange=&#039;checkName(this.value);&#039; /&gt;

&lt;p id=&#039;nStatus&#039;&gt;Please enter a name for your board.&lt;/p&gt;

...
</pre>
<p>You can see then that the value from the form field will be checked in the function which will send the data to a PHP file which we must now define.  Whatever that PHP file &#8220;responds&#8221; with (or echoes back) will be displayed in the &#8216;p&#8217; tag we defined below the input field.  So let&#8217;s finish it off with the PHP file which must check the name entered against the boards already existing in the MySQL database, leading to something like this:</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL...

$name = mysql_real_escape_string($_GET[&#039;n&#039;]);

//We&#039;re using the GET method here, but there are applications of POST

$getBoards = mysql_query(&quot;SELECT `id` FROM `boards` WHERE `name`=&#039;$name&#039;&quot;);

if (mysql_num_rows($getBoards) == 0) { echo &quot;OK&quot;; }

else { echo &quot;Taken&quot;; }

?&gt;
</pre>
<p>Depending on your application, the echoed strings would be changed and perhaps even a bit more complex, but these work fine for the basic application we worked through.</p>
<p>As I noted above, we used the GET method, just like what is used in normal forms, where variables are passed through the URL to be accessed by the PHP file.  However, POST can be used and should be used in certain situations.  In general, they coincide with the general rules for form method choosing.  GET should be used for shorter requests of one or two variables and POST for multiple fields and especially those sent to the database.  Remember that the URL from GET can only be so long before cut off and may not be able to hold all the information from a long request.  Therefore, POST is certainly the most viable choice because it can be used in all applications by simply altering the method in the JavaScript and PHP and adding a few lines as noted on the tutorials listed above.</p>
<p>Still wondering where AJAX can come in handy?  We&#8217;ve all seen those handy &#8220;username checks&#8221; on registration pages and the suggestions provided by Google, Yahoo!, YouTube, and other big-name websites, and these all employ AJAX.   Whether you realized it or not because of their speed, these pages actually utilize more code than a typical PHP/ASP check, but they have certain disadvantages and will always be <a href="http://www.webmaster-forums.net/html-css-and-javascript/is-ajax-worth-it">up for debate</a>.</p>


<p>Related posts:<ul><li><a href='http://phpstarter.net/2008/12/working-with-images-introducing-the-gd-library/' rel='bookmark' title='Permanent Link: Working with Images &#8211; Introducing the GD Library'>Working with Images &#8211; Introducing the GD Library</a></li><li><a href='http://phpstarter.net/2009/02/dynamically-converting-text-to-an-image/' rel='bookmark' title='Permanent Link: Dynamically Converting Text to an Image'>Dynamically Converting Text to an Image</a></li><li><a href='http://phpstarter.net/2008/12/run-codeigniter-from-the-command-line-ssh/' rel='bookmark' title='Permanent Link: Run CodeIgniter from the Command Line / SSH'>Run CodeIgniter from the Command Line / SSH</a></li></ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/03/working-with-ajax/feed/</wfw:commentRss>
		<slash:comments>2</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 [...]


Related posts:<ul><li><a href='http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/' rel='bookmark' title='Permanent Link: Parse Weather Forecast Data (from the NDFD) in PHP'>Parse Weather Forecast Data (from the NDFD) in PHP</a></li><li><a href='http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/' rel='bookmark' title='Permanent Link: Parse Current Weather Conditions Data from the NWS in PHP'>Parse Current Weather Conditions Data from the NWS in PHP</a></li><li><a href='http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/' rel='bookmark' title='Permanent Link: 5 Sources of Free Weather Data for your Site'>5 Sources of Free Weather Data for your Site</a></li></ul>]]></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>Related posts:<ul><li><a href='http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/' rel='bookmark' title='Permanent Link: Parse Weather Forecast Data (from the NDFD) in PHP'>Parse Weather Forecast Data (from the NDFD) in PHP</a></li><li><a href='http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/' rel='bookmark' title='Permanent Link: Parse Current Weather Conditions Data from the NWS in PHP'>Parse Current Weather Conditions Data from the NWS in PHP</a></li><li><a href='http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/' rel='bookmark' title='Permanent Link: 5 Sources of Free Weather Data for your Site'>5 Sources of Free Weather Data for your Site</a></li></ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/03/more-examples-with-parsing-ndfd-data-in-php/feed/</wfw:commentRss>
		<slash:comments>11</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 [...]


Related posts:<ul><li><a href='http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/' rel='bookmark' title='Permanent Link: 5 Sources of Free Weather Data for your Site'>5 Sources of Free Weather Data for your Site</a></li><li><a href='http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/' rel='bookmark' title='Permanent Link: Parse Weather Forecast Data (from the NDFD) in PHP'>Parse Weather Forecast Data (from the NDFD) in PHP</a></li><li><a href='http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/' rel='bookmark' title='Permanent Link: How to Get the Geographic Location of an IP Address'>How to Get the Geographic Location of an IP Address</a></li></ul>]]></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>Related posts:<ul><li><a href='http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/' rel='bookmark' title='Permanent Link: 5 Sources of Free Weather Data for your Site'>5 Sources of Free Weather Data for your Site</a></li><li><a href='http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/' rel='bookmark' title='Permanent Link: Parse Weather Forecast Data (from the NDFD) in PHP'>Parse Weather Forecast Data (from the NDFD) in PHP</a></li><li><a href='http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/' rel='bookmark' title='Permanent Link: How to Get the Geographic Location of an IP Address'>How to Get the Geographic Location of an IP Address</a></li></ul></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>0</slash:comments>
		</item>
		<item>
		<title>Regular Expressions May Cause Irregularity</title>
		<link>http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/</link>
		<comments>http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 06:00:14 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Intermediate]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=379</guid>
		<description><![CDATA[Regular expressions seem rather complex, even like a foreign language to beginning programmers.  The mixture of symbols and characters can bring you to tears if you have a limited understanding, but with the knowledge of the significance of each symbol and construct, regular expressions can bring you from irregularity to peaceful contention bliss.


Related posts:<ul><li><a href='http://phpstarter.net/2009/02/explosive-php-application/' rel='bookmark' title='Permanent Link: Explosive PHP Application'>Explosive PHP Application</a></li><li><a href='http://phpstarter.net/2009/04/loading-ini-files-in-php/' rel='bookmark' title='Permanent Link: Loading INI Files in PHP'>Loading INI Files in PHP</a></li><li><a href='http://phpstarter.net/2009/01/sort-posts-by-comment-count-in-wordpress/' rel='bookmark' title='Permanent Link: Sort Posts by Comment Count in Wordpress'>Sort Posts by Comment Count in Wordpress</a></li></ul>]]></description>
			<content:encoded><![CDATA[<p>Regular expressions seem rather complex, even like a foreign language to beginning programmers.  The mixture of symbols and characters can bring you to tears if you have a limited understanding, but with the knowledge of the significance of each symbol and construct, regular expressions can bring you from irregularity to peaceful contention bliss.<span id="more-379"></span>A regular expression (regex for short) is a pattern describing a string of text.  There are levels of complexity for regular expressions, from simple strings of literal characters to repetition and grouping.</p>
<p>The most basic regular expression consists of a single <strong>literal character</strong> like <em>a</em>.  It will match that character in a string, but only on the first time, unless you apply repetitive properties to it or are more specific.  To use literal symbols, <em>[</em>, <em>\</em>,<em> ^</em>,<em> $</em>,<em> .</em>,<em> |</em>,<em> ?</em>,<em> *</em>,<em> (</em>,<em> )</em> you must escape them with a backslash (<em>\</em>).   For example, <strong>1\+1=2</strong> is the correct regular expression to match <strong>1+1=2</strong>.</p>
<p>Next are character classes or character sets.  Instead of specifying each letter of the alphabet or digit, it is possible instead to use sets of alphanumeric characters to match a string.  For instance <strong>six[a-z]+</strong> matches <strong>sixteen</strong>, <strong>sixty</strong>, and <strong>sixlet</strong>, among others.  Charcter sets should be placed within brackets and can include any range of lower-case characters, upper-case characters, digits from 0 to 9, hyphens, and underscores.</p>
<p>Regular expressions do have some shorthand character classes to ease your mind:  <strong>\d</strong> for all digits, <strong>\w</strong> for all alphanumeric characters or the underscore (&#8221;_&#8221;), <strong>\s</strong> for whitespace characters including tabs and line breaks, <strong>\t</strong> for tabs individually, <strong>\r</strong> for carriage returns, and <strong>\n</strong> for line feeds.  Remember that Windows text files use <strong>\r\n</strong> to terminate lines while UNIX text files simply use <strong>\n</strong>.</p>
<p>The dot or period (&#8221;.&#8221;) stands for any character except line break characters, meaning the same as <strong>[^\n]</strong>, where the <strong>^</strong> character means the negation of the following character (&#8221;anything but &#8230;&#8221;).  Often times a character class or negated character class is faster and more precise, so be cautious when using the dot.</p>
<p>Alternation allows for some choice in your regular expressions.  Using the vertical pipe bar (&#8221;|&#8221;), you can make <strong>sixteen</strong>, <strong>sixty</strong>, and <strong>sixlet</strong> all match the following regular expression: <strong>six(teen|ty|let)</strong>.  The question mark (&#8221;?&#8221;) allows for optional characters, for instance when dealing with British-English and American-English spellings (<strong>colou?r </strong>matches <strong>color</strong> and <strong>colour</strong>).</p>
<p>Lastly is the issue of repetition.  The asterisk (&#8221;*&#8221;) tells the engine to atempt to match the class zero or more times.  The plus sign (&#8221;+&#8221;) tries to match one or more times.  An integer in curly brackets following a class can specify an exact amount of instances.</p>
<p>Now for some examples.  The description above can seem quite weighty and boring, but some applications should solidify the ideas and clarify any confusion.</p>
<p><strong>Format of an e-mail address</strong></p>
<pre class="brush: php">

&lt;?php

$goodEmail = &quot;yourname@yourdomain.com&quot;;

$badEmail = &quot;thisIsNoEmailAtAll&quot;;

$niceTry = &quot;thisIsClose@domain&quot;;

$tooManyAts = &quot;thisIsCloseToo@@domain&quot;;

if (@preg_match(&#039;/[-a-zA-Z0-9]+@{1}[-a-zA-Z0-9]+[\.]{1}[a-zA-Z]{2,4}[\.]*[-a-zA-Z0-9]*/&#039;, $email)) {

echo &quot;Good email!&quot;;

}

else {

echo &quot;The format of your e-mail address is unacceptable.&quot;;

}

?&gt;
</pre>
<p>You can run through each e-mail address above, and the one named as good will work while the others will fail.  Notice that we allow for three or four letter domains as well as those like &#8220;co.uk&#8221; where the domain would have two periods (&#8221;.&#8221;).</p>
<p>Another common use of regular expressions is in URL rewriting.  For instance, on my website, JeoReview, when a user access a URL like &#8216;http://www.jeoreview.com/board/Board-Name&#8217; a different page is served to show the board itself.  In truth, that URL does not exist.  The regular expression, as placed in the <strong>.htaccess</strong> file, looks like this:</p>
<pre class="brush: php">

Options FollowSymLinks
RewriteEngine On
RewriteRule ^board/(.+)$ loadboard.php?name=$1
</pre>
<p>The caret (&#8221;^&#8221;) marks the beginning of the string and the dollar sign (&#8221;$&#8221;) marks the end.  Because nearly any character can be used for the board name, a dot (&#8221;.&#8221;) is used to match the name itself.  In truth, the better alternative would be to match exactly what characters can be used to increase speed and accuracy.  In any case, the <strong>$1</strong> refers to the first character case, and each subsequent integer is filled with the following character cases, though in this example there is only one.</p>
<p>There are plenty of other great uses of regular expressions.  Check some out by visiting these great resources and cheat sheets:</p>
<ul>
<li>Regular-Expressions Reference (<a href="http://www.regular-expressions.info/reference.html">http://www.regular-expressions.info/reference.html</a>)</li>
<li>Regular Expression Checker (<a href="http://regjex.com/">http://regjex.com/</a>)</li>
<li>Cheat Sheet (<a href="http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/">http://www.addedbytes.com/cheat-sheets/regular-expressions-cheat-sheet/</a>)</li>
<li>Using Regular Expressions and PHP (<a href="http://www.regular-expressions.info/php.html">http://www.regular-expressions.info/php.html</a><cite>)</cite></li>
</ul>


<p>Related posts:<ul><li><a href='http://phpstarter.net/2009/02/explosive-php-application/' rel='bookmark' title='Permanent Link: Explosive PHP Application'>Explosive PHP Application</a></li><li><a href='http://phpstarter.net/2009/04/loading-ini-files-in-php/' rel='bookmark' title='Permanent Link: Loading INI Files in PHP'>Loading INI Files in PHP</a></li><li><a href='http://phpstarter.net/2009/01/sort-posts-by-comment-count-in-wordpress/' rel='bookmark' title='Permanent Link: Sort Posts by Comment Count in Wordpress'>Sort Posts by Comment Count in Wordpress</a></li></ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/regular-expressions-may-cause-irregularity/feed/</wfw:commentRss>
		<slash:comments>0</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 [...]


Related posts:<ul><li><a href='http://phpstarter.net/2009/03/more-examples-with-parsing-ndfd-data-in-php/' rel='bookmark' title='Permanent Link: More Examples with Parsing NDFD Data in PHP'>More Examples with Parsing NDFD Data in PHP</a></li><li><a href='http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/' rel='bookmark' title='Permanent Link: Parse Current Weather Conditions Data from the NWS in PHP'>Parse Current Weather Conditions Data from the NWS in PHP</a></li><li><a href='http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/' rel='bookmark' title='Permanent Link: 5 Sources of Free Weather Data for your Site'>5 Sources of Free Weather Data for your Site</a></li></ul>]]></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>Related posts:<ul><li><a href='http://phpstarter.net/2009/03/more-examples-with-parsing-ndfd-data-in-php/' rel='bookmark' title='Permanent Link: More Examples with Parsing NDFD Data in PHP'>More Examples with Parsing NDFD Data in PHP</a></li><li><a href='http://phpstarter.net/2009/02/parse-current-weather-conditions-data-from-the-nws-in-php/' rel='bookmark' title='Permanent Link: Parse Current Weather Conditions Data from the NWS in PHP'>Parse Current Weather Conditions Data from the NWS in PHP</a></li><li><a href='http://phpstarter.net/2008/12/5-sources-of-free-weather-data-for-your-site/' rel='bookmark' title='Permanent Link: 5 Sources of Free Weather Data for your Site'>5 Sources of Free Weather Data for your Site</a></li></ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/parse-weather-forecast-data-from-the-ndfd-in-php/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Basic PHP/MySQL Actions</title>
		<link>http://phpstarter.net/2009/02/basic-phpmysql-actions/</link>
		<comments>http://phpstarter.net/2009/02/basic-phpmysql-actions/#comments</comments>
		<pubDate>Tue, 17 Feb 2009 06:00:22 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[MySQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beginner]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=357</guid>
		<description><![CDATA[Using databases to store user identification, image information, and so much more for dynamic websites is the easiest way to ease maintenance. MySQL is the most popular choice of database, and in this article, I'll explain the most basic functions: connecting and using a MySQL database and its respective tables.


Related posts:<ul><li><a href='http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/' rel='bookmark' title='Permanent Link: How to Get the Geographic Location of an IP Address'>How to Get the Geographic Location of an IP Address</a></li><li><a href='http://phpstarter.net/2009/04/loading-ini-files-in-php/' rel='bookmark' title='Permanent Link: Loading INI Files in PHP'>Loading INI Files in PHP</a></li><li><a href='http://phpstarter.net/2008/12/very-basic-pie-chart/' rel='bookmark' title='Permanent Link: Very Basic Pie Chart'>Very Basic Pie Chart</a></li></ul>]]></description>
			<content:encoded><![CDATA[<p>Using databases to store user identification, image information, and so much more for dynamic websites is the easiest way to ease maintenance.  MySQL is the most popular choice of database, and in this article, I&#8217;ll explain the most basic functions: connecting and using a MySQL database and its respective tables.<span id="more-357"></span>The first step in using a MySQL database is to make sure your host has the necessities set up.  Typically, your web host&#8217;s control panel will allow the creation of a database/user pair which will allow you to connect.  However, most do not allow the creation of these directly through a PHP script.  Check with your host to see how you can get your MySQL database running.</p>
<p>The next step, and probably the first in your running script is connecting to the user and database, using the following two functions:</p>
<pre class="brush: php">

&lt;?php

...

mysql_connect(host, user, password);

mysql_select_db(database [, link]);

...

?&gt;
</pre>
<p>Again, your host will work with you with respect to establishing the user, password, and database, and <em>host</em> is typically &#8220;localhost&#8221; when accessing the database on the same server as your website, but check with your host if you are having problems.  The link, which is optional, would refer to the variable holding your <strong>mysql_connect()</strong> reference.</p>
<p>Now you have a database ready to go, but without a table, there&#8217;s no place for your streams of data to go, so let&#8217;s set one up.  Most of our queries to MySQL are going to be run through the appropriately named <strong>mysql_query()</strong> function, and the text within will change with each different application.  To create a table, we run a query like this:</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL before running any queries, every time

mysql_query(&quot;CREATE TABLE table_name(

column_one ATTRIBUTES,

column_two ATTRIBUTES,

...

)&quot;);

mysql_close(link);

?&gt;
</pre>
<p>You should take the time before creating a table to decide what all needs to be stored and what would be the best manner to do so, and then use one of the column types and attributes name <a href="http://dev.mysql.com/doc/refman/5.1/en/create-table.html" target="_blank">at this resource</a>.  Some may seem confusing, but there are plenty of elaborations and tutorials available to describe the uses of each type.  The <strong>mysql_close()</strong> function simply closes our the defined connection and is typically unnecessary as the connection will be closed at the end of the script anyway.</p>
<p>With a table available for queries, we can begin adding and working with our data.  The main abilities available with the <strong>mysql_query()</strong> function our <strong>SELECT</strong>, <strong>SHOW</strong>, <strong>DESCRIBE</strong>, <strong>EXPLAIN</strong>, <strong>INSERT</strong>, <strong>UPDATE</strong>, <strong>DELETE</strong>, and <strong>DROP</strong>.  The first four return a resource (explained in detail in a minute) and the latter four return a boolean value depending on the success.</p>
<p><strong>SHOW</strong>, <strong>DESCRIBE</strong>, and <strong>EXPLAIN</strong> are honestly rarely used within the context of a functioning, user-run website.  They are moreso used on the administrator&#8217;s end and even then are not as functional as the others.  <strong>DELETE</strong> and <strong>DROP</strong> should certainly only be used on the administrator&#8217;s end and probably, again, only through MySQL itself and not through a publicly-available executable file.  Only through proper authentication should someone be able to delete a record or even an entire MySQL table.</p>
<p>Let&#8217;s start with <strong>INSERT</strong>, as that is where you must start to use the other functions.  To insert data into a table, run the function like this:</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL before running any queries, every time

mysql_query(&quot;INSERT INTO `table_name` (col1, col2, ...)

VALUES(&#039;val1&#039;, &#039;val2&#039;, ...)&quot;) or die(mysql_error());

...

?&gt;
</pre>
<p>The column names in the first set of parentheses should correspond with the correct value in the second set.  You may also opt, with each execution of <strong>mysql_query()</strong> to use the <strong>mysql_error()</strong> function to report an error should one occur, though hopefully you&#8217;ve worked your script well and an error is handled by your own error-checking.  However, some things do slip by and happen unpreventably.</p>
<p>Next is the <strong>SELECT</strong> application.  Just as it sounds, you select records from an identified table and can then use the data however you wish, by displaying it, checking it against variables, etc.  Either way, a <strong>SELECT</strong> application looks like this:</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL before running any queries, every time

$getRows = mysql_query(&quot;SELECT * FROM `table_name` WHERE `col_name`=&#039;val&#039;&quot;);

while ($result = mysql_fetch_array($getRows)) {

echo $result[&#039;col_name&#039;];

...

}

...

?&gt;
</pre>
<p>The <strong>*</strong> can be replaced with each column you wish to extract, separated by commas, and the WHERE clause is in the query is optional but should be used when looking for particular records.  You should note that <strong>SELECT</strong> returns a resource, so we have to loop through that resource using the <strong>mysql_fetch_array()</strong>, <strong>mysql_fetch_assoc()</strong>, <strong>mysql_fetch_row()</strong> or an appropriate alternative.  Then the data from the records is stored in an array where each column is referenced by its respective name.</p>
<p>To delete a record (or records) use a similar construct to the <strong>SELECT</strong> application, but no looping or variable-calling is necessary.  It simply works through the query:</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL before running any queries, every time

mysql_query(&quot;DELETE FROM `table_name` WHERE `col_name`=&#039;val&#039;&quot;);

...

?&gt;
</pre>
<p>To delete an entire table, use the <strong>DROP</strong> application, though realize that every record will be obliterated:</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL before running any queries, every time

mysql_query(&quot;DROP TABLE `table_name`&quot;);

...

?&gt;
</pre>
<p>Lastly, editing records is fairly easy though it can be more cumbersome.  Using the <strong>UPDATE</strong> application like so can allow for the altering of preexisting rows.</p>
<pre class="brush: php">

&lt;?php

//Connect to MySQL before running any queries, every time

mysql_query(&quot;UPDATE `table_name`

SET `col_name` = &#039;val&#039;, `col2_name` = &#039;val2&#039;, ...

WHERE `col_name` = &#039;val&#039;&quot;);

...
?&gt;
</pre>
<p>You can change as many columns as you need, separating each with a comma, but be careful with spacing because the success of the update can depend highly on the spacing as I have seen in the past, though I can&#8217;t find a good reference on what the exact spacing should look like.</p>
<p>With these basic applications in tow, little cannot be accomplished with your MySQL database.  With a dynamic, user-driven website these will certainly be integrated into your website.  To keep a more watchful eye on your database and perform certain one-time actions on your tables, you may also choose to employ a GUI like <a href="http://www.phpmyadmin.net" target="_blank">PHPMyAdmin</a> or something similar which your host may already have available through the control panel.</p>
<p>Happy querying!</p>


<p>Related posts:<ul><li><a href='http://phpstarter.net/2008/12/how-to-get-the-geographic-location-of-an-ip-address/' rel='bookmark' title='Permanent Link: How to Get the Geographic Location of an IP Address'>How to Get the Geographic Location of an IP Address</a></li><li><a href='http://phpstarter.net/2009/04/loading-ini-files-in-php/' rel='bookmark' title='Permanent Link: Loading INI Files in PHP'>Loading INI Files in PHP</a></li><li><a href='http://phpstarter.net/2008/12/very-basic-pie-chart/' rel='bookmark' title='Permanent Link: Very Basic Pie Chart'>Very Basic Pie Chart</a></li></ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/basic-phpmysql-actions/feed/</wfw:commentRss>
		<slash:comments>0</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, [...]


Related posts:<ul><li><a href='http://phpstarter.net/2009/03/working-with-ajax/' rel='bookmark' title='Permanent Link: Working with AJAX'>Working with AJAX</a></li><li><a href='http://phpstarter.net/2009/01/load-rss-feeds-into-php-arrays-with-lastrss/' rel='bookmark' title='Permanent Link: Load RSS Feeds into PHP Arrays with lastRSS'>Load RSS Feeds into PHP Arrays with lastRSS</a></li><li><a href='http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/' rel='bookmark' title='Permanent Link: Locate the Nearest Radar Station and Display Radar Images'>Locate the Nearest Radar Station and Display Radar Images</a></li></ul>]]></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>Related posts:<ul><li><a href='http://phpstarter.net/2009/03/working-with-ajax/' rel='bookmark' title='Permanent Link: Working with AJAX'>Working with AJAX</a></li><li><a href='http://phpstarter.net/2009/01/load-rss-feeds-into-php-arrays-with-lastrss/' rel='bookmark' title='Permanent Link: Load RSS Feeds into PHP Arrays with lastRSS'>Load RSS Feeds into PHP Arrays with lastRSS</a></li><li><a href='http://phpstarter.net/2009/01/locate-the-nearest-radar-station-and-display-radar-images/' rel='bookmark' title='Permanent Link: Locate the Nearest Radar Station and Display Radar Images'>Locate the Nearest Radar Station and Display Radar Images</a></li></ul></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>
		<item>
		<title>Explosive PHP Application</title>
		<link>http://phpstarter.net/2009/02/explosive-php-application/</link>
		<comments>http://phpstarter.net/2009/02/explosive-php-application/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 06:00:18 +0000</pubDate>
		<dc:creator>Kurtis</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Beginner]]></category>

		<guid isPermaLink="false">http://phpstarter.net/?p=341</guid>
		<description><![CDATA[Sometimes a complex PHP-built website can become tedious when dealing with minor changes to the template and HTML markup.  Changing, for instance, a set of links (navigation) or other integral parts of a website, can become quite the lengthy process.  In this article, I'll share a technique that I sometimes use to make something as simple as a website navigation a little more automated using an explosive function.


Related posts:<ul><li><a href='http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/' rel='bookmark' title='Permanent Link: Separating the Application &#038; Presentation and Alternative Syntax'>Separating the Application &#038; Presentation and Alternative Syntax</a></li><li><a href='http://phpstarter.net/2009/01/sort-posts-by-comment-count-in-wordpress/' rel='bookmark' title='Permanent Link: Sort Posts by Comment Count in Wordpress'>Sort Posts by Comment Count in Wordpress</a></li><li><a href='http://phpstarter.net/2008/12/scatter-plots-an-application-of-the-gd-library/' rel='bookmark' title='Permanent Link: Scatter plots &#8211; An Application of the GD Library'>Scatter plots &#8211; An Application of the GD Library</a></li></ul>]]></description>
			<content:encoded><![CDATA[<p>Sometimes a complex PHP-built website can become tedious when dealing with minor changes to the template and HTML markup.  Changing, for instance, a set of links (navigation) or other integral parts of a website, can become quite the lengthy process.  In this article, I&#8217;ll share a technique that I sometimes use to make something as simple as a website navigation a little more automated using an explosive function.<span id="more-341"></span>So maybe you&#8217;ve caught on to the references to explosions and are thinking that something&#8217;s about to get dangerous, and really, this application is quite safe and easy to use.  The function itself is properly named &#8220;explode&#8221;:</p>
<p><span>
<pre class="brush: php">

&lt;?php

...

$arr = explode(delimiter, string [,limit]);

...

?&gt;
</pre>
<p>Now you may be thinking: that&#8217;s all well in good but what in the world is a delimiter?  I thought the same way before I truly understood the function.  The delimiter is just the common separator between each element.  For instance, if we wanted to explode a sentence into an array with each element as a separate word from the string, the delimiter would be an empty space (&#8221; &#8220;).  The optional &#8220;limit&#8221; is a limit of the number of elements to allow to be created.  If it is left empty or set to &#8220;-1,&#8221; no limit will be set.  Otherwise, once the limit is reached, the last element will be the rest of the unexploded string.</p>
<p>Now this is all good and well unless you have an awesome application of the function, and believe me, there are many, but my favorite is the dynamic navigation idea.  I always get sick of having to add in all the extra template elements when altering a website&#8217;s navigation, and with this simple idea that can cease.</p>
<p>Here&#8217;s a basic run-down of what will happen:  first, we&#8217;ll define a string holding all the link names and source locations.  Then, we&#8217;ll explode that string to an array of all link name-source pairs which we will in turn explode individually to produce a great link.  Here&#8217;s an example:</p>
<pre class="brush: php">

&lt;?php

...

$links = &quot;Home:index.php,About Us:about.php,Contact Us:contact.php,Portfolio:portfolio.php&quot;;

$links = explode(&quot;,&quot;,$links);

echo &quot;&lt;ul&gt;&quot;;

foreach ($links as $link) {

$link = explode(&quot;:&quot;,$link);

echo &quot;&lt;li&gt;&lt;a href=&#039;&quot;.$link[1].&quot;&#039;&gt;&quot;.$link[0].&quot;&lt;/a&gt;&lt;/li&gt;&quot;;

}

echo &quot;&lt;/ul&gt;&quot;;

?&gt;
</pre>
<p>Be aware of the order in which we are exploding the elements.  If you explode incorrectly, you could end up with inaccurate pairs.  With this application, to update the navigation, instead of sifting through what could become complex HTML, you simply need to edit the &#8220;links&#8221; variable and let the PHP take care of business for you.  Nothing complex, but certainly useful.</p>


<p>Related posts:<ul><li><a href='http://phpstarter.net/2009/03/separating-the-application-presentation-and-alternative-syntax/' rel='bookmark' title='Permanent Link: Separating the Application &#038; Presentation and Alternative Syntax'>Separating the Application &#038; Presentation and Alternative Syntax</a></li><li><a href='http://phpstarter.net/2009/01/sort-posts-by-comment-count-in-wordpress/' rel='bookmark' title='Permanent Link: Sort Posts by Comment Count in Wordpress'>Sort Posts by Comment Count in Wordpress</a></li><li><a href='http://phpstarter.net/2008/12/scatter-plots-an-application-of-the-gd-library/' rel='bookmark' title='Permanent Link: Scatter plots &#8211; An Application of the GD Library'>Scatter plots &#8211; An Application of the GD Library</a></li></ul></p>]]></content:encoded>
			<wfw:commentRss>http://phpstarter.net/2009/02/explosive-php-application/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.442 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2009-07-04 01:20:41 -->
<!-- Compression = gzip -->