<?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>David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞. &#187; PHP</title> <atom:link href="http://davidwalsh.name/tutorials/php/feed" rel="self" type="application/rss+xml" /><link>http://davidwalsh.name</link> <description>Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</description> <lastBuildDate>Thu, 02 Sep 2010 03:13:15 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.0.1</generator> <item><title>Quick Tip:  Object Indexing vs. Array&#160;Collection</title><link>http://davidwalsh.name/object-array-index</link> <comments>http://davidwalsh.name/object-array-index#comments</comments> <pubDate>Thu, 26 Aug 2010 13:47:13 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Optimization]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5052</guid> <description><![CDATA[The Setup &#38;&#160;Goal Let&#8217;s say that we have one large text document and we have a a bunch of keywords that we want to parse the document for.  We don&#8217;t care how many times times the keyword appears &#8212; we just care that it&#8217;s been used.  When we find a keyword, we need to record [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/object-array-index">Quick Tip:  Object Indexing vs. Array&nbsp;Collection</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/element-collection-manipulation-shortcut-using-mootools' rel='bookmark' title='Permanent Link: Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2'>Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/implementing-array-count-method-javascript' rel='bookmark' title='Permanent Link: Implementing an Array.count() Method in&nbsp;JavaScript'>Implementing an Array.count() Method in&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/dojo-connect' rel='bookmark' title='Permanent Link: dojo.connect: A Powerful Object and Event&nbsp;Listener'>dojo.connect: A Powerful Object and Event&nbsp;Listener</a></li><li><a
href='http://davidwalsh.name/array-shuffling-mootools' rel='bookmark' title='Permanent Link: Implement Array Shuffling in&nbsp;MooTools'>Implement Array Shuffling in&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/access-object-properties' rel='bookmark' title='Permanent Link: Access JavaScript Object Variable&nbsp;Properties'>Access JavaScript Object Variable&nbsp;Properties</a></li></ol>]]></description> <content:encoded><![CDATA[<h2>The Setup &amp;&nbsp;Goal</h2><p>Let&#8217;s say that we have one large text document and we have a a bunch of keywords that we want to parse the document for.  We don&#8217;t care how many times times the keyword appears &#8212; we just care that it&#8217;s been used.  When we find a keyword, we need to record that keyword been found so that we may check at a later time.</p><h2>Inefficient Method:  Array Collection and&nbsp;Search</h2><p>The first method to record that a keyword has been found is by pushing the keyword into one array:</p><pre class="js">
//Assume an array called "foundKeywords" was defined above
if(shouldSave(keyword)) {
	foundKeywords.push(keyword);
}
</pre><p>At the end of the document search, we&#8217;d end up with an array like:</p><pre class="js">
//the foundKeywords array looks like:
//['keyword1','keyword2','keyword2',...]
</pre><p>When it comes to checking this array for the existence of a given keyword, this method will prove inefficient.  Why?  Because we&#8217;d need to loop through the array and search until we found the given keyword (if ever).  Those are a lot of &#8220;wasted&#8221; or fruitless cycles, even if we break the loop when the keyword was found.  Inefficient is the only word to describe this process.</p><h2>The Efficient Method:  Object with&nbsp;Index</h2><p>The fastest method of checking a storing keywords for later reference is by object (in JavaScript) or associative array (in PHP).  Instead of adding the keyword to an array, we add the keyword as an index to a master object, giving the value as 1:</p><pre class="js">
//Assume an object {} called "foundKeywords" was defined above
if(shouldSave(keyword)) {
	foundKeywords[keyword] = 1;
}
</pre><p>Why is this faster?  No wasted cycles looking blindly through an array.  The check is quick and simple:</p><pre class="js">
if(foundKeywords[keyword]) { //FOUND!
	//do something
}
</pre><p>It&#8217;s either an index or it&#8217;s not!  In PHP, we&#8217;d save the keyword to an associative array:</p><pre class="php">
//Assume an array called "$found_keywords" was defined above
if(shouldSave($keyword)) {
	$found_keywords[$keyword] = 1;
}

//Later: checking if the keyword was there...
if($found_keywords[$keyword]) { //or array_key_exists($keyword,$found_keywords)
	//FOUND!
}
</pre><p>In a word&#8230;awesome.  Not only fast but simple!</p><p>I cannot provide a benchmark because the speed of execution depends on how large the keyword array is.  Suffice to say, for the sake of simplicity and speed, using an object with keyword index is definitely the way to go!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/object-array-index">Quick Tip:  Object Indexing vs. Array&nbsp;Collection</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/element-collection-manipulation-shortcut-using-mootools' rel='bookmark' title='Permanent Link: Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2'>Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/implementing-array-count-method-javascript' rel='bookmark' title='Permanent Link: Implementing an Array.count() Method in&nbsp;JavaScript'>Implementing an Array.count() Method in&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/dojo-connect' rel='bookmark' title='Permanent Link: dojo.connect: A Powerful Object and Event&nbsp;Listener'>dojo.connect: A Powerful Object and Event&nbsp;Listener</a></li><li><a
href='http://davidwalsh.name/array-shuffling-mootools' rel='bookmark' title='Permanent Link: Implement Array Shuffling in&nbsp;MooTools'>Implement Array Shuffling in&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/access-object-properties' rel='bookmark' title='Permanent Link: Access JavaScript Object Variable&nbsp;Properties'>Access JavaScript Object Variable&nbsp;Properties</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/object-array-index/feed</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Change Category Slug within&#160;WordPress</title><link>http://davidwalsh.name/wordpress-category-slug</link> <comments>http://davidwalsh.name/wordpress-category-slug#comments</comments> <pubDate>Thu, 12 Aug 2010 14:16:04 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[APIs]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5037</guid> <description><![CDATA[When I first started this blog, I set the category &#8220;slug&#8221; to &#8220;sugar.&#8221;  Why sugar?  Because a lot of a good thing is candy;  thus, a bunch of MooTools tutorials is as sweet as sugar.  While I get a giggle out of calling my categories sugar, Google doesn&#8217;t find it nearly as funny, nor does [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/wordpress-category-slug">Change Category Slug within&nbsp;WordPress</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/php-wordpress-post-categories' rel='bookmark' title='Permanent Link: PHP: Get WordPress Post&nbsp;Categories'>PHP: Get WordPress Post&nbsp;Categories</a></li><li><a
href='http://davidwalsh.name/detect-ipad' rel='bookmark' title='Permanent Link: iPad Detection Using JavaScript or&nbsp;PHP'>iPad Detection Using JavaScript or&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/april-fools-change-php-pages-asp' rel='bookmark' title='Permanent Link: April Fools!  Change Your PHP Pages to ASP&#8230;Or&nbsp;Not'>April Fools!  Change Your PHP Pages to ASP&#8230;Or&nbsp;Not</a></li><li><a
href='http://davidwalsh.name/change-php-query-string-variable-separator-php-ini' rel='bookmark' title='Permanent Link: Change the PHP Query String Variable Separator Using&nbsp;php.ini'>Change the PHP Query String Variable Separator Using&nbsp;php.ini</a></li><li><a
href='http://davidwalsh.name/php-redirect-function' rel='bookmark' title='Permanent Link: PHP Redirect&nbsp;Function'>PHP Redirect&nbsp;Function</a></li></ol>]]></description> <content:encoded><![CDATA[<p>When I first started this blog, I set the category &#8220;slug&#8221; to &#8220;sugar.&#8221;  Why sugar?  Because a lot of a good thing is candy;  thus, a bunch of MooTools tutorials is as sweet as sugar.  While I get a giggle out of calling my categories sugar, Google doesn&#8217;t find it nearly as funny, nor does Yahoo or Bing.  In an effort to increase my SEO, I wanted to change my category slug to &#8220;tutorials.&#8221;  That&#8217;s where the awesome Redirection plugin and a simple regular expression comes into place.</p><h2>Changing the&nbsp;Slug</h2><p>You can very easily change the category slug within WordPress&#8217;s admin panel by navigating to Settings &gt;&gt; Permalinks:</p><img
src="http://davidwalsh.name/dw-content/wordpress-category-slug.jpg" alt="WordPress Category" /><p>I changed the slug from &#8220;sugar&#8221; to &#8220;tutorials.&#8221;</p><h2>WordPress&nbsp;Redirection</h2><p>So why do we need the <a
href="http://wordpress.org/extend/plugins/redirection/">Redirection plugin</a>?  Because search engines like Google and users who have bookmarked your site will try to reach the old address.  Thus, we need an appropriate redirect to push them to the new address.  Not only do we need a redirection plugin but we need it to be reliable.  I&#8217;ve been using Redirection for <em>years</em> so I knew this would be the best route.</p><p>While Redirection allows you to make a simple URL to URL redirection, I needed something a bit more powerful since almost anything could be after &#8220;/sugar/&#8221; in the URL.  What I did was use Redirection&#8217;s regular expression capabilities to create a wildcard search on the URL to redirect all &#8220;/sugar/&#8221; URLs to &#8220;/tutorials/&#8221; URLS:</p><img
src="http://davidwalsh.name/dw-content/wordpress-redirection.jpg" alt=" WordPress Redirection" /><p>And there I have it;  all category URLs are redirected as they should be!  The <code>(*)</code> in the source URL grabs the text after &#8220;/sugar/&#8221; in the URL and the <code>$1</code> in the Target URL places that text after the new category slug!</p><p>The Redirection plugin for WordPress is outstanding.  As I mentioned above, I&#8217;ve used it for years, have hundreds of redirections in place, and it&#8217;s always been one of my most trusted plugins.  Thanks to <a
href="http://profiles.wordpress.org/users/johnny5">John Godley</a> for his great plugin!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/wordpress-category-slug">Change Category Slug within&nbsp;WordPress</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/php-wordpress-post-categories' rel='bookmark' title='Permanent Link: PHP: Get WordPress Post&nbsp;Categories'>PHP: Get WordPress Post&nbsp;Categories</a></li><li><a
href='http://davidwalsh.name/detect-ipad' rel='bookmark' title='Permanent Link: iPad Detection Using JavaScript or&nbsp;PHP'>iPad Detection Using JavaScript or&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/april-fools-change-php-pages-asp' rel='bookmark' title='Permanent Link: April Fools!  Change Your PHP Pages to ASP&#8230;Or&nbsp;Not'>April Fools!  Change Your PHP Pages to ASP&#8230;Or&nbsp;Not</a></li><li><a
href='http://davidwalsh.name/change-php-query-string-variable-separator-php-ini' rel='bookmark' title='Permanent Link: Change the PHP Query String Variable Separator Using&nbsp;php.ini'>Change the PHP Query String Variable Separator Using&nbsp;php.ini</a></li><li><a
href='http://davidwalsh.name/php-redirect-function' rel='bookmark' title='Permanent Link: PHP Redirect&nbsp;Function'>PHP Redirect&nbsp;Function</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/wordpress-category-slug/feed</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Build HTML Tables From MySQL Tables with&#160;PHP</title><link>http://davidwalsh.name/html-mysql-php</link> <comments>http://davidwalsh.name/html-mysql-php#comments</comments> <pubDate>Wed, 21 Jul 2010 16:55:40 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Markup]]></category> <category><![CDATA[MooTools]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5012</guid> <description><![CDATA[I was recently completing a project which required that I build a series of HTML tables which would represent all of the tables within a MySQL database.  I didn&#8217;t have anything created but after a few minutes I had exactly what I needed. Hopefully this helps you out! View Demo The&#160;CSS table.db-table { border-right:1px solid [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/html-mysql-php">Build HTML Tables From MySQL Tables with&nbsp;PHP</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/php-mysql-database-optimization-function' rel='bookmark' title='Permanent Link: PHP / MySQL Database Optimization&nbsp;Function'>PHP / MySQL Database Optimization&nbsp;Function</a></li><li><a
href='http://davidwalsh.name/backup-mysql-database-php' rel='bookmark' title='Permanent Link: Backup Your MySQL Database Using&nbsp;PHP'>Backup Your MySQL Database Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/php-calendar' rel='bookmark' title='Permanent Link: Build a Calendar Using PHP, XHTML, and&nbsp;CSS'>Build a Calendar Using PHP, XHTML, and&nbsp;CSS</a></li><li><a
href='http://davidwalsh.name/php-microsoft-sql-server-mssql-iis-connect-query-odbc' rel='bookmark' title='Permanent Link: PHP, Microsoft SQL Server (MSSQL), and IIS:  Connect and Query with&nbsp;ODBC'>PHP, Microsoft SQL Server (MSSQL), and IIS:  Connect and Query with&nbsp;ODBC</a></li><li><a
href='http://davidwalsh.name/web-service-php-mysql-xml-json' rel='bookmark' title='Permanent Link: Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON'>Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a></li></ol>]]></description> <content:encoded><![CDATA[<p>I was recently completing a project which required that I build a series of HTML tables which would represent all of the tables within a MySQL database.  I didn&#8217;t have anything created but after a few minutes I had exactly what I needed. Hopefully this helps you out!</p><p><a
href="http://davidwalsh.name/dw-content/build-mysql-tables.php"><img
src="http://davidwalsh.name/dw-content/mysql-db-tables.jpg" alt="" class="image" /></a></p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/build-mysql-tables.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;CSS</h2><pre class="css">
table.db-table 		{ border-right:1px solid #ccc; border-bottom:1px solid #ccc; }
table.db-table th	{ background:#eee; padding:5px; border-left:1px solid #ccc; border-top:1px solid #ccc; }
table.db-table td	{ padding:5px; border-left:1px solid #ccc; border-top:1px solid #ccc; }
</pre><p>The CSS I&#8217;m styling the table with is as basic as it gets &#8212; style as you wish!</p><h2>The PHP /&nbsp;MySQL</h2><pre class="php">
/* connect to the db */
$connection = mysql_connect('localhost','username','password');
mysql_select_db('my_db',$connection);

/* show tables */
$result = mysql_query('SHOW TABLES',$connection) or die('cannot show tables');
while($tableName = mysql_fetch_row($result)) {

	$table = $tableName[0];
	
	echo '&lt;h3&gt;',$table,'&lt;/h3&gt;';
	$result2 = mysql_query('SHOW COLUMNS FROM '.$table) or die('cannot show columns from '.$table);
	if(mysql_num_rows($result2)) {
		echo '&lt;table cellpadding="0" cellspacing="0" class="db-table"&gt;';
		echo '&lt;tr&gt;&lt;th&gt;Field&lt;/th&gt;&lt;th&gt;Type&lt;/th&gt;&lt;th&gt;Null&lt;/th&gt;&lt;th&gt;Key&lt;/th&gt;&lt;th&gt;Default&lt;th&gt;Extra&lt;/th&gt;&lt;/tr&gt;';
		while($row2 = mysql_fetch_row($result2)) {
			echo '&lt;tr&gt;';
			foreach($row2 as $key=&gt;$value) {
				echo '&lt;td&gt;',$value,'&lt;/td&gt;';
			}
			echo '&lt;/tr&gt;';
		}
		echo '&lt;/table&gt;&lt;br /&gt;';
	}
}
</pre><p>The first step in the process is accessing all of the tables within the database.  Once all tables have been fetched, the next step is to loops through the array of tables we receive and, for each table, build a new HTML table with column information.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/build-mysql-tables.php" class="demo">View Demo</a><div
class="clear"></div></div><p>Nothing groundbreaking but surely has use.  I&#8217;ve also written a blog post about backing up your MySQL database with PHP titled <a
href="http://davidwalsh.name/backup-mysql-database-php">Backup Your MySQL Database Using PHP</a>;  check that out if you&#8217;d prefer to backup your databse information in SQL format!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/html-mysql-php">Build HTML Tables From MySQL Tables with&nbsp;PHP</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/php-mysql-database-optimization-function' rel='bookmark' title='Permanent Link: PHP / MySQL Database Optimization&nbsp;Function'>PHP / MySQL Database Optimization&nbsp;Function</a></li><li><a
href='http://davidwalsh.name/backup-mysql-database-php' rel='bookmark' title='Permanent Link: Backup Your MySQL Database Using&nbsp;PHP'>Backup Your MySQL Database Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/php-calendar' rel='bookmark' title='Permanent Link: Build a Calendar Using PHP, XHTML, and&nbsp;CSS'>Build a Calendar Using PHP, XHTML, and&nbsp;CSS</a></li><li><a
href='http://davidwalsh.name/php-microsoft-sql-server-mssql-iis-connect-query-odbc' rel='bookmark' title='Permanent Link: PHP, Microsoft SQL Server (MSSQL), and IIS:  Connect and Query with&nbsp;ODBC'>PHP, Microsoft SQL Server (MSSQL), and IIS:  Connect and Query with&nbsp;ODBC</a></li><li><a
href='http://davidwalsh.name/web-service-php-mysql-xml-json' rel='bookmark' title='Permanent Link: Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON'>Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/html-mysql-php/feed</wfw:commentRss> <slash:comments>15</slash:comments> </item> <item><title>Create a &#8220;Recent Posts&#8221; Module Outside of&#160;WordPress</title><link>http://davidwalsh.name/wordpress-recent-posts</link> <comments>http://davidwalsh.name/wordpress-recent-posts#comments</comments> <pubDate>Fri, 16 Apr 2010 13:15:33 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4951</guid> <description><![CDATA[The websites I create are never powered by WordPress. Sure I may add a blog to the website but I&#8217;ve never created a client website that was run by the powerful blogging software. In an effort to tie the website and blog together, I&#8217;ll usually do some quick PHP/MySQL programming to pull in recent blog [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/wordpress-recent-posts">Create a &#8220;Recent Posts&#8221; Module Outside of&nbsp;WordPress</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/web-service-php-mysql-xml-json' rel='bookmark' title='Permanent Link: Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON'>Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a></li><li><a
href='http://davidwalsh.name/wp_query' rel='bookmark' title='Permanent Link: Create WordPress Page Templates with Custom&nbsp;Queries'>Create WordPress Page Templates with Custom&nbsp;Queries</a></li><li><a
href='http://davidwalsh.name/environment-php-server-module-reporter' rel='bookmark' title='Permanent Link: Know Your Environment: PHP Server Module&nbsp;Reporter'>Know Your Environment: PHP Server Module&nbsp;Reporter</a></li><li><a
href='http://davidwalsh.name/mootools-scrollspy-load' rel='bookmark' title='Permanent Link: Using MooTools ScrollSpy to Load More Items via&nbsp;JSON/AJAX'>Using MooTools ScrollSpy to Load More Items via&nbsp;JSON/AJAX</a></li><li><a
href='http://davidwalsh.name/mootools-drag-drop' rel='bookmark' title='Permanent Link: Using MooTools 1.2 For Drag, Drop, Sort,&nbsp;Save'>Using MooTools 1.2 For Drag, Drop, Sort,&nbsp;Save</a></li></ol>]]></description> <content:encoded><![CDATA[<p>The websites I create are never powered by WordPress.  Sure I may add a blog to the website but I&#8217;ve never created a client website that was run by the powerful blogging software.  In an effort to tie the website and blog together, I&#8217;ll usually do some quick PHP/MySQL programming to pull in recent blog post titles and links to the individual posts.  Here&#8217;s the PHP and MySQL that accomplishes that task.</p><h2>The&nbsp;SQL</h2><pre class="sql">
SELECT post_title, post_name 
FROM wp_posts 
WHERE post_type = 'post' 
AND post_status = 'publish' 
ORDER BY post_date DESC 
LIMIT 5
</pre><p>I&#8217;m simply choosing to pull the post title and slug &#8212; you can use &#8220;*&#8221; to pull in all fields or select additional fields by naming them.  The key to the SQL is making sure you use the WHERE conditionals above so you avoid pulling in revisions and unpublished posts.</p><h2>The&nbsp;PHP</h2><pre class="php">
$query = "SELECT post_title, post_name FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 5";
$result = mysql_query($query,$dblink);
if(mysql_num_rows($result)) {
	echo '&lt;ul&gt;';
	while($post = mysql_fetch_assoc($result)) {
		echo '&lt;li&gt;&lt;a href="/blog/',$post['post_name'],'"&gt;',stripslashes($post['post_title']),'&lt;/a&gt;&lt;/li&gt;';
	}
	echo '&lt;/ul&gt;';
}
</pre><p>The PHP above outputs the posts returned by our query into a nice UL/LI list.  As always, feel free to style the list as you wish!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/wordpress-recent-posts">Create a &#8220;Recent Posts&#8221; Module Outside of&nbsp;WordPress</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/web-service-php-mysql-xml-json' rel='bookmark' title='Permanent Link: Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON'>Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a></li><li><a
href='http://davidwalsh.name/wp_query' rel='bookmark' title='Permanent Link: Create WordPress Page Templates with Custom&nbsp;Queries'>Create WordPress Page Templates with Custom&nbsp;Queries</a></li><li><a
href='http://davidwalsh.name/environment-php-server-module-reporter' rel='bookmark' title='Permanent Link: Know Your Environment: PHP Server Module&nbsp;Reporter'>Know Your Environment: PHP Server Module&nbsp;Reporter</a></li><li><a
href='http://davidwalsh.name/mootools-scrollspy-load' rel='bookmark' title='Permanent Link: Using MooTools ScrollSpy to Load More Items via&nbsp;JSON/AJAX'>Using MooTools ScrollSpy to Load More Items via&nbsp;JSON/AJAX</a></li><li><a
href='http://davidwalsh.name/mootools-drag-drop' rel='bookmark' title='Permanent Link: Using MooTools 1.2 For Drag, Drop, Sort,&nbsp;Save'>Using MooTools 1.2 For Drag, Drop, Sort,&nbsp;Save</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/wordpress-recent-posts/feed</wfw:commentRss> <slash:comments>31</slash:comments> </item> <item><title>Create Bit.ly Short URLs Using PHP: API Version&#160;3</title><link>http://davidwalsh.name/bitly-api-php</link> <comments>http://davidwalsh.name/bitly-api-php#comments</comments> <pubDate>Thu, 08 Apr 2010 17:10:56 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4950</guid> <description><![CDATA[Bit.ly is a great URL shortening service. I love their reliability, shortness of the URL, and the information they provide about a given URL. Recently Bit.ly updated their API to version 3 so I thought I&#8217;d update my original Bit.ly post. Here&#8217;s how you can create short URLs and expand short URLs using Bit.ly. The&#160;PHP [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/bitly-api-php">Create Bit.ly Short URLs Using PHP: API Version&nbsp;3</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/bitly-php' rel='bookmark' title='Permanent Link: Create Bit.ly Short URLs Using&nbsp;PHP'>Create Bit.ly Short URLs Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/create-short-urls-unu' rel='bookmark' title='Permanent Link: Create Short URLs Using&nbsp;U.Nu'>Create Short URLs Using&nbsp;U.Nu</a></li><li><a
href='http://davidwalsh.name/create-digg-url-php' rel='bookmark' title='Permanent Link: Create Digg URLs Using&nbsp;PHP'>Create Digg URLs Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/isgd-url-php' rel='bookmark' title='Permanent Link: Create an Is.Gd URL Using&nbsp;PHP'>Create an Is.Gd URL Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/create-tiny-url-php' rel='bookmark' title='Permanent Link: Create a TinyURL with&nbsp;PHP'>Create a TinyURL with&nbsp;PHP</a></li></ol>]]></description> <content:encoded><![CDATA[<p><a
href="http://bit.ly/" rel="nofollow">Bit.ly</a> is a great URL shortening service.  I love their reliability, shortness of the URL, and the information they provide about a given URL.  Recently Bit.ly updated their API to version 3 so I thought I&#8217;d update my original <a
href="http://davidwalsh.name/bitly-php">Bit.ly post</a>.  Here&#8217;s how you can create short URLs and expand short URLs using Bit.ly.</p><h2>The&nbsp;PHP</h2><pre class="php">
/* returns the shortened url */
function get_bitly_short_url($url,$login,$appkey,$format='txt') {
	$connectURL = 'http://api.bit.ly/v3/shorten?login='.$login.'&#038;apiKey='.$appkey.'&#038;uri='.urlencode($url).'&#038;format='.$format;
	return curl_get_result($connectURL);
}

/* returns expanded url */
function get_bitly_long_url($url,$login,$appkey,$format='txt') {
	$connectURL = 'http://api.bit.ly/v3/expand?login='.$login.'&#038;apiKey='.$appkey.'&#038;shortUrl='.urlencode($url).'&#038;format='.$format;
	return curl_get_result($connectURL);
}

/* returns a result form url */
function curl_get_result($url) {
	$ch = curl_init();
	$timeout = 5;
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
	$data = curl_exec($ch);
	curl_close($ch);
	return $data;
}

/* get the short url */
$short_url = get_bitly_short_url('http://davidwalsh.name/','davidwalshblog','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

/* get the long url from the short one */
$long_url = get_bitly_long_url($short_url,'davidwalshblog','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
</pre><p>All you really need to is pass your appkey and login (you must sign up for their API service), the long or short URL, and the format which you&#8217;d like the result to be returned in.  If you just want a simple URL with no other information, use the default &#8220;txt&#8221; format.  Retrieving the XML or JSON formats will provide you more information about the URL.</p><p>Bit.ly is awesome.  I mean, Twitter uses them &#8212; what more of an endorsement would you need.</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/bitly-api-php">Create Bit.ly Short URLs Using PHP: API Version&nbsp;3</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/bitly-php' rel='bookmark' title='Permanent Link: Create Bit.ly Short URLs Using&nbsp;PHP'>Create Bit.ly Short URLs Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/create-short-urls-unu' rel='bookmark' title='Permanent Link: Create Short URLs Using&nbsp;U.Nu'>Create Short URLs Using&nbsp;U.Nu</a></li><li><a
href='http://davidwalsh.name/create-digg-url-php' rel='bookmark' title='Permanent Link: Create Digg URLs Using&nbsp;PHP'>Create Digg URLs Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/isgd-url-php' rel='bookmark' title='Permanent Link: Create an Is.Gd URL Using&nbsp;PHP'>Create an Is.Gd URL Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/create-tiny-url-php' rel='bookmark' title='Permanent Link: Create a TinyURL with&nbsp;PHP'>Create a TinyURL with&nbsp;PHP</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/bitly-api-php/feed</wfw:commentRss> <slash:comments>13</slash:comments> </item> <item><title>iPad Detection Using JavaScript or&#160;PHP</title><link>http://davidwalsh.name/detect-ipad</link> <comments>http://davidwalsh.name/detect-ipad#comments</comments> <pubDate>Wed, 07 Apr 2010 13:43:20 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4948</guid> <description><![CDATA[The hottest device out there right now seems to be the iPad. iPad this, iPad that, iPod your mom. I&#8217;m underwhelmed with the device but that doesn&#8217;t mean I shouldn&#8217;t try to account for such devices on the websites I create. In Apple&#8217;s developer tip sheet they provide the iPad&#8217;s user agent string: Mozilla/5.0 (iPad; [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/detect-ipad">iPad Detection Using JavaScript or&nbsp;PHP</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/detect-iphone' rel='bookmark' title='Permanent Link: iPhone &#038; iPod Detection Using&nbsp;JavaScript'>iPhone &#038; iPod Detection Using&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/google-password-protected-areas' rel='bookmark' title='Permanent Link: Allow Google Into Password Protected&nbsp;Areas'>Allow Google Into Password Protected&nbsp;Areas</a></li><li><a
href='http://davidwalsh.name/set-user-agent-php-curl-spoof' rel='bookmark' title='Permanent Link: Set the User Agent With PHP&nbsp;cURL'>Set the User Agent With PHP&nbsp;cURL</a></li><li><a
href='http://davidwalsh.name/php-redirect-function' rel='bookmark' title='Permanent Link: PHP Redirect&nbsp;Function'>PHP Redirect&nbsp;Function</a></li><li><a
href='http://davidwalsh.name/zoom-mobile-browsers' rel='bookmark' title='Permanent Link: Prevent Page Zooming in Mobile&nbsp;Browsers'>Prevent Page Zooming in Mobile&nbsp;Browsers</a></li></ol>]]></description> <content:encoded><![CDATA[<img
src="http://davidwalsh.name/dw-content/ipads.png" alt="iPad" class="image" /><p>The hottest device out there right now seems to be the iPad.  iPad this, iPad that, iPod your mom.  I&#8217;m underwhelmed with the device but that doesn&#8217;t mean I shouldn&#8217;t try to account for such devices on the websites I create.  In Apple&#8217;s developer tip sheet they provide the iPad&#8217;s user agent string:</p><pre class="text">
Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10
</pre><p>Given that string we can create a few code snippets to determine if the user is being a smug, iPad-using bastard.</p><h2>The&nbsp;JavaScript</h2><pre class="js">
var isiPad = navigator.userAgent.match(/iPad/i) != null;
</pre><p>A quick String.match regular expression test can check for the presence of &#8220;iPad&#8221; in the user agent string.</p><h2>The&nbsp;PHP</h2><pre class="php">
$isiPad = (bool) strpos($_SERVER['HTTP_USER_AGENT'],'iPad');
</pre><p>This time we look for the position of &#8220;iPad&#8221; in the user agent string.</p><h2>The&nbsp;.htaccess</h2><pre class="text">
RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
RewriteRule ^(.*)$ http://ipad.yourdomain.com [R=301]
</pre><p>Using some logic from Drew Douglass&#8217; excellent <a
href="http://dev-tips.com/featured/redirect-iphone-blackberry-palm-requests-with-htaccess" rel="nofollow">mobile redirection post</a>, we can redirect users to a mobile version of your website if you so desire.</p><p>So what would you the above tests for?  You may want to redirect iPad users to a different version of your website.  You may want to implement different styles to your standard website if your user is surfing on an iPad.</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/detect-ipad">iPad Detection Using JavaScript or&nbsp;PHP</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/detect-iphone' rel='bookmark' title='Permanent Link: iPhone &#038; iPod Detection Using&nbsp;JavaScript'>iPhone &#038; iPod Detection Using&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/google-password-protected-areas' rel='bookmark' title='Permanent Link: Allow Google Into Password Protected&nbsp;Areas'>Allow Google Into Password Protected&nbsp;Areas</a></li><li><a
href='http://davidwalsh.name/set-user-agent-php-curl-spoof' rel='bookmark' title='Permanent Link: Set the User Agent With PHP&nbsp;cURL'>Set the User Agent With PHP&nbsp;cURL</a></li><li><a
href='http://davidwalsh.name/php-redirect-function' rel='bookmark' title='Permanent Link: PHP Redirect&nbsp;Function'>PHP Redirect&nbsp;Function</a></li><li><a
href='http://davidwalsh.name/zoom-mobile-browsers' rel='bookmark' title='Permanent Link: Prevent Page Zooming in Mobile&nbsp;Browsers'>Prevent Page Zooming in Mobile&nbsp;Browsers</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/detect-ipad/feed</wfw:commentRss> <slash:comments>21</slash:comments> </item> <item><title>Automatically Generate a Photo Gallery from a Directory of Images:&#160;Updated</title><link>http://davidwalsh.name/generate-photo-gallery</link> <comments>http://davidwalsh.name/generate-photo-gallery#comments</comments> <pubDate>Tue, 06 Apr 2010 14:01:11 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[CSS]]></category> <category><![CDATA[Markup]]></category> <category><![CDATA[MooTools]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4944</guid> <description><![CDATA[Two years ago Chris Coyier wrote an outstanding tutorial detailing how you can generate a photo gallery based on the images within two directories: a thumbnails directory and an originals directory. I&#8217;ve decided to take his tutorial a step further by showing you how to generate thumbnails for the gallery using PHP. I&#8217;ve also implemented [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/generate-photo-gallery">Automatically Generate a Photo Gallery from a Directory of Images:&nbsp;Updated</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/create-image-thumbnail-php' rel='bookmark' title='Permanent Link: Create Image Thumbnails Using&nbsp;PHP'>Create Image Thumbnails Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/slideshow-preload-images' rel='bookmark' title='Permanent Link: Create a Quick MooTools Slideshow with Preloading&nbsp;Images'>Create a Quick MooTools Slideshow with Preloading&nbsp;Images</a></li><li><a
href='http://davidwalsh.name/remove-internet-explorers-gallery-image-toolbar' rel='bookmark' title='Permanent Link: Remove Internet Explorer&#8217;s Gallery Image&nbsp;Toolbar'>Remove Internet Explorer&#8217;s Gallery Image&nbsp;Toolbar</a></li><li><a
href='http://davidwalsh.name/pngcrush-directory' rel='bookmark' title='Permanent Link: PNGCRUSH a Directory of&nbsp;Images'>PNGCRUSH a Directory of&nbsp;Images</a></li><li><a
href='http://davidwalsh.name/password-protect-directory-using-htaccess' rel='bookmark' title='Permanent Link: Password Protect a Directory Using&nbsp;.htaccess'>Password Protect a Directory Using&nbsp;.htaccess</a></li></ol>]]></description> <content:encoded><![CDATA[<a
href="http://davidwalsh.name/dw-content/generate-photo-gallery.php"><img
src="http://davidwalsh.name/dw-content/preload-images-thumbs/2.jpg" alt="PHP Photo Gallery" class="image" /></a><p>Two years ago Chris Coyier wrote an outstanding tutorial detailing <a
href="http://scriptandstyle.com/automatically-generate-a-photo-gallery-from-a-directory-of-images" rel="nofollow">how you can generate a photo gallery</a> based on the images within two directories:  a thumbnails directory and an originals directory.  I&#8217;ve decided to take his tutorial a step further by showing you how to generate thumbnails for the gallery using PHP.  I&#8217;ve also implemented a MooTools lightbox: <a
href="http://gueschla.com/labs/smoothbox/" rel="nofollow">Smoothbox</a>.  The following code will show you how to create a beautiful photo gallery by simply dumping your photos in a directory.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/generate-photo-gallery.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;CSS</h2><pre class="css">
.clear			{ clear:both; }
.photo-link		{ padding:5px; margin:5px; border:1px solid #ccc; display:block; width:200px; float:left; }
.photo-link:hover	{ border-color:#999; }
</pre><p>The images/links will be floated next to each other.  The other option would be to use a table.  Booooo.</p><h2>The PHP:  Utility Functions</h2><pre class="php">
/* function:  generates thumbnail */
function make_thumb($src,$dest,$desired_width) {
	/* read the source image */
	$source_image = imagecreatefromjpeg($src);
	$width = imagesx($source_image);
	$height = imagesy($source_image);
	/* find the "desired height" of this thumbnail, relative to the desired width  */
	$desired_height = floor($height*($desired_width/$width));
	/* create a new, "virtual" image */
	$virtual_image = imagecreatetruecolor($desired_width,$desired_height);
	/* copy source image at a resized size */
	imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height);
	/* create the physical thumbnail image to its destination */
	imagejpeg($virtual_image,$dest);
}

/* function:  returns files from dir */
function get_files($images_dir,$exts = array('jpg')) {
	$files = array();
	if($handle = opendir($images_dir)) {
		while(false !== ($file = readdir($handle))) {
			$extension = strtolower(get_file_extension($file));
			if($extension &amp;&amp; in_array($extension,$exts)) {
				$files[] = $file;
			}
		}
		closedir($handle);
	}
	return $files;
}

/* function:  returns a file's extension */
function get_file_extension($file_name) {
	return substr(strrchr($file_name,'.'),1);
}
</pre><p>We&#8217;ll use three utility functions to make the system work:  get_files (retrieves all of the files in a given directory), get_file_extension, and make_thumb (generates a thumbnail image from a source image).  These are good functions to keep at hand for other purposes too.</p><h2>The PHP:  Setting and HTML&nbsp;Generation</h2><pre class="php">
/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
$thumbs_width = 200;
$images_per_row = 3;

/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
	$index = 0;
	foreach($image_files as $index=&gt;$file) {
		$index++;
		$thumbnail_image = $thumbs_dir.$file;
		if(!file_exists($thumbnail_image)) {
			$extension = get_file_extension($thumbnail_image);
			if($extension) {
				make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
			}
		}
		echo '&lt;a href="',$images_dir.$file,'" class="photo-link smoothbox" rel="gallery"&gt;&lt;img src="',$thumbnail_image,'" /&gt;&lt;/a&gt;';
		if($index % $images_per_row == 0) { echo '&lt;div class="clear"&gt;&lt;/div&gt;'; }
	}
	echo '&lt;div class="clear"&gt;&lt;/div&gt;';
}
else {
	echo '&lt;p&gt;There are no images in this gallery.&lt;/p&gt;';
}
</pre><p>The first step is to define a few simple settings which will dictate image paths, the width by which all thumbnails will be created, and the number of images per row.  The action begins with rounding up all of the files.  With every image in the gallery, we check to see if a thumbnail exists.  If a thumbnail doesn&#8217;t exist, we use PHP and the utility function above to generate one.  When the thumbnail is generated (or there was one there in the first place), we output the HTML link/image.  I&#8217;ve given the A element the &#8220;smoothbox&#8221; CSS class so that Smoothbox  will make the larger image display in the lightbox.</p><h2>The MooTools JavaScript /&nbsp;Smoothbox</h2><p>All you need to do is include the JavaScript file.  Sweet.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/generate-photo-gallery.php" class="demo">View Demo</a><div
class="clear"></div></div><p>That&#8217;s it!  Have any features you&#8217;d like to see added?  Let me know!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/generate-photo-gallery">Automatically Generate a Photo Gallery from a Directory of Images:&nbsp;Updated</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/create-image-thumbnail-php' rel='bookmark' title='Permanent Link: Create Image Thumbnails Using&nbsp;PHP'>Create Image Thumbnails Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/slideshow-preload-images' rel='bookmark' title='Permanent Link: Create a Quick MooTools Slideshow with Preloading&nbsp;Images'>Create a Quick MooTools Slideshow with Preloading&nbsp;Images</a></li><li><a
href='http://davidwalsh.name/remove-internet-explorers-gallery-image-toolbar' rel='bookmark' title='Permanent Link: Remove Internet Explorer&#8217;s Gallery Image&nbsp;Toolbar'>Remove Internet Explorer&#8217;s Gallery Image&nbsp;Toolbar</a></li><li><a
href='http://davidwalsh.name/pngcrush-directory' rel='bookmark' title='Permanent Link: PNGCRUSH a Directory of&nbsp;Images'>PNGCRUSH a Directory of&nbsp;Images</a></li><li><a
href='http://davidwalsh.name/password-protect-directory-using-htaccess' rel='bookmark' title='Permanent Link: Password Protect a Directory Using&nbsp;.htaccess'>Password Protect a Directory Using&nbsp;.htaccess</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/generate-photo-gallery/feed</wfw:commentRss> <slash:comments>57</slash:comments> </item> <item><title>Using MooTools ScrollSpy to Load More Items via&#160;JSON/AJAX</title><link>http://davidwalsh.name/mootools-scrollspy-load</link> <comments>http://davidwalsh.name/mootools-scrollspy-load#comments</comments> <pubDate>Tue, 09 Feb 2010 14:20:05 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[CSS]]></category> <category><![CDATA[Markup]]></category> <category><![CDATA[MooTools]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4755</guid> <description><![CDATA[Last July I wrote an epic dominant unbelievable fantastic outstanding awesome NetTuts post called Create a Twitter-Like &#8220;Load More&#8221; Widget Using CSS, HTML, JSON, and jQuery or MooTools where I used a MooTools/AJAX/JSON system for loading additional items when the user clicks a &#8220;Load More&#8221; link. The functionality is sweet but I see room for [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/mootools-scrollspy-load">Using MooTools ScrollSpy to Load More Items via&nbsp;JSON/AJAX</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/web-service-php-mysql-xml-json' rel='bookmark' title='Permanent Link: Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON'>Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a></li><li><a
href='http://davidwalsh.name/scrollspy-terms' rel='bookmark' title='Permanent Link: Scrolling &#8220;Agree to Terms&#8221; Component with MooTools&nbsp;ScrollSpy'>Scrolling &#8220;Agree to Terms&#8221; Component with MooTools&nbsp;ScrollSpy</a></li><li><a
href='http://davidwalsh.name/google-load' rel='bookmark' title='Permanent Link: google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API'>google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API</a></li><li><a
href='http://davidwalsh.name/dynamically-load-stylesheets-mootools' rel='bookmark' title='Permanent Link: Dynamically Load Stylesheets Using MooTools&nbsp;1.2'>Dynamically Load Stylesheets Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/get-reddit-score' rel='bookmark' title='Permanent Link: Get a URL&#8217;s Reddit Score Using PHP and&nbsp;JSON'>Get a URL&#8217;s Reddit Score Using PHP and&nbsp;JSON</a></li></ol>]]></description> <content:encoded><![CDATA[<a
href="http://davidwalsh.name/dw-content/scrollspy-load-more.php"><img
src="http://davidwalsh.name/dw-content/nettuts2.jpg" alt="MooTools ScrollSpy Load More" class="image" /></a><p>Last July I wrote an <span
style="text-decoration: line-through;">epic</span> <span
style="text-decoration: line-through;">dominant</span> <span
style="text-decoration: line-through;">unbelievable</span> <span
style="text-decoration: line-through;">fantastic</span> <span
style="text-decoration: line-through;">outstanding</span> awesome NetTuts post called <a
href="http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/">Create a Twitter-Like &#8220;Load More&#8221; Widget Using CSS, HTML, JSON, and jQuery or MooTools</a> where I used a MooTools/AJAX/JSON system for loading additional items when the user clicks a &#8220;Load More&#8221; link.  The functionality is sweet but I see room for improvement.  If a user scrolls down toward the end of the container, why not load more items for them automatically?  Armed with the premier MooTools scrolling plugin, <a
href="http://mootools.net/forge/p/scrollspy">ScrollSpy</a>, we can do so.</p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/scrollspy-load-more.php" class="demo">View Demo</a> <a
href="http://mootools.net/forge/p/scrollspy" class="demo">Download ScrollSpy</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><pre class="html">

<div id="posts-container">
	
	<div id="posts"></div>
	
	<div id="load-more">Load More</div>
</div>

</pre><p>As you can see, the page starts with very little HTML.  Obviously this isn&#8217;t solution which will work without JavaScript enabled.  Making this system work without JavaScript wouldn&#8217;t be too difficult&#8230;but we&#8217;ll skip that in this tutorial.</p><h2>The&nbsp;CSS</h2><pre class="html">
#posts	{ height:300px; overflow:scroll; }
</pre><p>The CSS from my original NetTuts stays the same &#8212; we simply added the #posts selector properties.</p><h2>The MooTools&nbsp;JavaScript</h2><p>Quite a bit gets added to the original tutorials so I&#8217;ll point out each change individually:</p><pre class="js">
/* via @appden, Scott Kyle, http://appden.com/javascript/fun-with-custom-events-on-elements-in-mootools/ */
Native.implement([Element, Window, Document, Events], {
	oneEvent: function(type, fn) {
		return this.addEvent(type, function() {
			this.removeEvent(type, arguments.callee);
			return fn.apply(this, arguments);
		});
	}
});
</pre><p>The code above represents a function that gets run only once per element.  We&#8217;ll use this in a moment.</p><pre class="js">
//NEW!
var spy;
var spyContainer = $('posts');
var spyAct = function() {
	var min = spyContainer.getScrollSize().y - spyContainer.getSize().y - 150 /* tolerance */;
	spy = new ScrollSpy({
		container: spyContainer,
		min: min,
		onEnter: function() {
			loadMore.fireEvent('click');
		}
	});
};
//wait for first load...
window.oneEvent('load',function() {
	spyAct();
});
</pre><p>We create the ScrollSpy listener to keep track of scrolling.  If the user scrolls within 150 pixels of the bottom, we fire a virtual click on the &#8220;Load More&#8221; link.</p><pre class="js">
//Request.JSON above....
onSuccess: function(responseJSON) {
	//reset the message
	loadMore.set('text','Load More');
	//increment the current status
	start += desiredPosts;
	//add in the new posts
	postHandler(responseJSON);
	//spy calc!
	spyAct();
},
//more below....
</pre><p>Lastly, we call the worker function on the JSON request&#8217;s success event.  Here&#8217;s the entire MooTools JavaScript snippet:</p><pre class="js">
/* via @appden, Scott Kyle, http://appden.com/javascript/fun-with-custom-events-on-elements-in-mootools/ */
Native.implement([Element, Window, Document, Events], {
	oneEvent: function(type, fn) {
		return this.addEvent(type, function() {
			this.removeEvent(type, arguments.callee);
			return fn.apply(this, arguments);
		});
	}
});


//safety closure
(function($) {
	//domready event
	window.addEvent('domready',function() {
		//settings on top
		var domain = 'http://davidwalsh.name/';
		var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']);  ?>;
		var start = <?php echo $_SESSION['posts_start']; ?>;
		var desiredPosts = <?php echo $number_of_posts; ?>;
		var loadMore = $('load-more');
		//NEW!
		var spy;
		var spyContainer = $('posts');
		var spyAct = function() {
			var min = spyContainer.getScrollSize().y - spyContainer.getSize().y - 150 /* tolerance */;
			spy = new ScrollSpy({
				container: spyContainer,
				min: min,
				onEnter: function() {
					loadMore.fireEvent('click');
				}
			});
		};
		//wait for first load...
		window.oneEvent('load',function() {
			spyAct();
		});
		//function that creates the posts
		var postHandler = function(postsJSON) {
			postsJSON.each(function(post,i) {
				//post url
				var postURL = '' + domain + post.post_name;
				//create the HTML
				var postDiv = new Element('div',{
					'class': 'post',
					events: {
						click: function() {
							window.location = postURL;
						}
					},
					id: 'post-' + post.ID,
					html: '<a href="' + postURL + '" class="post-title">' + post.post_title + '</a><p class="post-content">' + post.post_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>'
				});
				//inject into the container
				postDiv.inject($('posts'));
			});
			
		};
		
		//place the initial posts in the page
		postHandler(initialPosts);
		
		//ajax!
		var request = new Request.JSON({
			url: 'load-more.php', //ajax script -- same page
			method: 'get',
			link: 'cancel',
			noCache: true,
			onRequest: function() {
				//add the activate class and change the message
				loadMore.addClass('activate').set('text','Loading...');
			},
			onSuccess: function(responseJSON) {
				//reset the message
				loadMore.set('text','Load More');
				//increment the current status
				start += desiredPosts;
				//add in the new posts
				postHandler(responseJSON);
				//spy calc!
				spyAct();
			},
			onFailure: function() {
				//reset the message
				loadMore.set('text','Oops! Try Again.');
			},
			onComplete: function() {
				//remove the spinner
				loadMore.removeClass('activate');
			}
		});
		//add the "Load More" click event
		loadMore.addEvent('click',function(){
			//begin the ajax attempt
			request.send({
				data: {
					'start': start,
					'desiredPosts': desiredPosts
				}
			});
		});
	});
})(document.id);
</pre><h2>The&nbsp;PHP</h2><p>The following PHP loads more items.  My example uses WordPress posts:</p><pre class="php">
/* settings */
session_start();
$number_of_posts = 5; //5 at a time
$_SESSION['posts_start'] = $_SESSION['posts_start'] ? $_SESSION['posts_start'] : $number_of_posts;

/* loading of stuff */
if(isset($_GET['start'])) {
	/* spit out the posts within the desired range */
	echo get_posts($_GET['start'],$_GET['desiredPosts']);
	/* save the user's "spot", so to speak */
	//$_SESSION['posts_start']+= $_GET['desiredPosts'];
	/* kill the page */
	die();
}

/* grab stuff */
function get_posts($start = 0, $number_of_posts = 5) {
	/* connect to the db */
	$connection = mysql_connect('localhost','username','password');
	mysql_select_db('blogname',$connection);
	$posts = array();
	/* get the posts */
	$query = "SELECT post_title, post_content, post_name, ID FROM wp_posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT $start,$number_of_posts";
	$result = mysql_query($query);
	while($row = mysql_fetch_assoc($result)) {
		preg_match("/<p>(.*)<\/p>/",$row['post_content'],$matches);
		$row['post_content'] = strip_tags($matches[1]);
		$posts[] = $row;
	}
	/* return the posts in the JSON format */
	return json_encode($posts);
}
</pre><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/scrollspy-load-more.php" class="demo">View Demo</a> <a
href="http://mootools.net/forge/p/scrollspy" class="demo">Download ScrollSpy</a><div
class="clear"></div></div><h2>A Few&nbsp;Thoughts</h2><ul><li>This type of system only works well if you remember how many items were last loaded.  Making the user start from the default number is annoying as hell.</li><li>I&#8217;ve found that listening for scrolling is browsers is shotty &#8212; sometimes browsers simply don&#8217;t fire the scroll event properly, which makes the &#8220;Load More&#8221; link all the more important.</li></ul><p>If you want an in-depth description of the system, please <a
href="http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/">read the original post at NetTuts</a>.</p><p>Cool functionality though, huh?</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/mootools-scrollspy-load">Using MooTools ScrollSpy to Load More Items via&nbsp;JSON/AJAX</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/web-service-php-mysql-xml-json' rel='bookmark' title='Permanent Link: Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON'>Create a Basic Web Service Using PHP, MySQL, XML, and&nbsp;JSON</a></li><li><a
href='http://davidwalsh.name/scrollspy-terms' rel='bookmark' title='Permanent Link: Scrolling &#8220;Agree to Terms&#8221; Component with MooTools&nbsp;ScrollSpy'>Scrolling &#8220;Agree to Terms&#8221; Component with MooTools&nbsp;ScrollSpy</a></li><li><a
href='http://davidwalsh.name/google-load' rel='bookmark' title='Permanent Link: google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API'>google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API</a></li><li><a
href='http://davidwalsh.name/dynamically-load-stylesheets-mootools' rel='bookmark' title='Permanent Link: Dynamically Load Stylesheets Using MooTools&nbsp;1.2'>Dynamically Load Stylesheets Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/get-reddit-score' rel='bookmark' title='Permanent Link: Get a URL&#8217;s Reddit Score Using PHP and&nbsp;JSON'>Get a URL&#8217;s Reddit Score Using PHP and&nbsp;JSON</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/mootools-scrollspy-load/feed</wfw:commentRss> <slash:comments>13</slash:comments> </item> <item><title>ID Your Body Using&#160;PHP</title><link>http://davidwalsh.name/id-body-php</link> <comments>http://davidwalsh.name/id-body-php#comments</comments> <pubDate>Wed, 03 Feb 2010 14:08:09 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4743</guid> <description><![CDATA[It seems like every part of a website needs to be dynamic. Dynamic, database-driven pages, dynamic JavaScript, dynamic CSS, etc. All this dynamism can make it difficult to style or script a page easily. One way I&#8217;ve learned to combat the rigidness of using CMS&#8217; is to give the BODY element a unique ID based [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/id-body-php">ID Your Body Using&nbsp;PHP</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/iis-php-server-request_uri' rel='bookmark' title='Permanent Link: Fixing IIS &#038; PHP Variables &#8211; Set $_SERVER['REQUEST_URI']&nbsp;Yourself'>Fixing IIS &#038; PHP Variables &#8211; Set $_SERVER['REQUEST_URI']&nbsp;Yourself</a></li><li><a
href='http://davidwalsh.name/get-body-using-mootools' rel='bookmark' title='Permanent Link: Grab the Body Using&nbsp;MooTools'>Grab the Body Using&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/force-secure-page-php' rel='bookmark' title='Permanent Link: Force A Secure Page Using&nbsp;PHP'>Force A Secure Page Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/dynamic-functions' rel='bookmark' title='Permanent Link: Create PHP Classes with Dynamic&nbsp;Functions'>Create PHP Classes with Dynamic&nbsp;Functions</a></li><li><a
href='http://davidwalsh.name/wordpress-404' rel='bookmark' title='Permanent Link: WordPress, 404s, and Load&nbsp;Time'>WordPress, 404s, and Load&nbsp;Time</a></li></ol>]]></description> <content:encoded><![CDATA[<p>It seems like every part of a website needs to be dynamic.  Dynamic, database-driven pages, dynamic JavaScript, dynamic CSS, etc.  All this dynamism can make it difficult to style or script a page easily.  One way I&#8217;ve learned to combat the rigidness of using CMS&#8217; is to give the BODY element a unique ID based on the URL.  Doing so allows me to add special styling to any page.</p><h2>The&nbsp;PHP</h2><pre class="php">
function generate_id($uri) {
	/* regular expressions */
	$regex1 = '/[^a-zA-Z0-9]/'; //remove anything but letters and numbers
	$regex2 = '/[\-]+/'; //remove multiple &quot;-&quot;'s in a row
	$regex3 = '/^[-]+/'; //remove starting &quot;-&quot;
	$regex4 = '/[-]+$/'; //remove ending &quot;-&quot;
	/* return... */
	return preg_replace(
				array($regex1,$regex2,$regex3,$regex4),
				array('-','-','',''),
				$_SERVER['REQUEST_URI']
			  );
}

/* do it! */
$body_id = generate_id($_SERVER['REQUEST_URI']);
</pre><p>The above code uses preg_replace to find &#8220;bad&#8221; or repeated characters and replace them with dashes or nothing.  I don&#8217;t claim to be a regular expression genius so there may be a better way to  construct the preg_replace regex parameters.  Let&#8217;s take a look at some example usages:</p><pre class="php">
//assuming the page URI is:  /some-directory/deeper/my-page
$body_id = generate_id($_SERVER['REQUEST_URI']);
//returns:  some-directory-deeper-my-page
echo '&lt;body id=&quot;',$body_id,'&quot;&gt;';
</pre><p>The above uses the page URI to build out the body ID, joining the &#8220;page name&#8221; with its directory.</p><pre class="php">
//assuming the page URI is:  /some-directory/deeper/my-page?category=mootools
$body_id = generate_id($_SERVER['REQUEST_URI']);
//returns:  some-directory-deeper-my-page-category-mootools
echo '&lt;body id=&quot;',$body_id,'&quot;&gt;';
</pre><p>The above uses the page URI, including the GET parameters.</p><pre class="php">
//assuming the page URI is:  /some-directory/deeper/my-page.php?category=mootools
$body_id = generate_id($_SERVER['REQUEST_URI']);
//returns:  some-directory-deeper-my-page-php-category-mootools
echo '&lt;body id=&quot;',$body_id,'&quot;&gt;';
</pre><p>The above shows how a non-search-engine-friendly URL being parsed.  If you&#8217;d like, you can <a
href="http://davidwalsh.name/php-function-get-file-extension-string">remove  the &#8220;.php&#8221; file extension</a> from the URI.</p><h2>Using&nbsp;CSS</h2><pre class="css">
body#my-dir-my-page	{ /* custom formatting for this page */ }
</pre><p>The above shows you how you can leverage the new ID to your advantage when it comes to specialty CSS for the given page.</p><h2>A Few&nbsp;Thoughts</h2><ul><li>I&#8217;ve chose to use the ID attribute &#8212; you could easily make it a CSS class instead.  Since this generated string should be unique (at least theoretically), I prefer the ID.</li><li>If you aren&#8217;t using SEF links, I recommend removing the file extension &#8212; if not just for cleanliness.</li><li>Keep the query string parameters if they&#8217;re relevant/unique per that page.  You may want to make the page the ID and add a class of the querystring parameters:<pre class="php">
//assuming the page URI is:  /some-directory/deeper/my-page?category=mootools
list($id,$class) = explode('?',$_SERVER['REQUEST_URI']);
echo '&lt;body id=&quot;',$id,'&quot; class=&quot;',$class,'&quot;&gt;';
//returns:  &lt;body id=&quot;some-directory-deeper-my-page&quot; class=&quot;category-mootools&quot;&gt;
</pre></li></ul><p>What are your thoughts?  Do you do anything like this?</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/id-body-php">ID Your Body Using&nbsp;PHP</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/iis-php-server-request_uri' rel='bookmark' title='Permanent Link: Fixing IIS &#038; PHP Variables &#8211; Set $_SERVER['REQUEST_URI']&nbsp;Yourself'>Fixing IIS &#038; PHP Variables &#8211; Set $_SERVER['REQUEST_URI']&nbsp;Yourself</a></li><li><a
href='http://davidwalsh.name/get-body-using-mootools' rel='bookmark' title='Permanent Link: Grab the Body Using&nbsp;MooTools'>Grab the Body Using&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/force-secure-page-php' rel='bookmark' title='Permanent Link: Force A Secure Page Using&nbsp;PHP'>Force A Secure Page Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/dynamic-functions' rel='bookmark' title='Permanent Link: Create PHP Classes with Dynamic&nbsp;Functions'>Create PHP Classes with Dynamic&nbsp;Functions</a></li><li><a
href='http://davidwalsh.name/wordpress-404' rel='bookmark' title='Permanent Link: WordPress, 404s, and Load&nbsp;Time'>WordPress, 404s, and Load&nbsp;Time</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/id-body-php/feed</wfw:commentRss> <slash:comments>23</slash:comments> </item> <item><title>Replace Content in PRE Tags with HTML&#160;Entities</title><link>http://davidwalsh.name/php-html-entities</link> <comments>http://davidwalsh.name/php-html-entities#comments</comments> <pubDate>Thu, 28 Jan 2010 14:37:51 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Markup]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4663</guid> <description><![CDATA[If you have a website that relies heavily on PRE tags, you know the important of converting PRE tag content to their HTML entities. Doing so prevents worlds of possible rendering issues. The following PHP snippet HTML-Entitizes (?) any code within PRE tags: //replaces pre content with html entities function pre_entities($matches) { return str_replace($matches[1],htmlentities($matches[1]),$matches[0]); } [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/php-html-entities">Replace Content in PRE Tags with HTML&nbsp;Entities</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/format-code-pre-tags' rel='bookmark' title='Permanent Link: Format Code Inside PRE Tags within TextMate Using&nbsp;PHP'>Format Code Inside PRE Tags within TextMate Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/nobr-css' rel='bookmark' title='Permanent Link: Replace NOBR Tags with&nbsp;CSS'>Replace NOBR Tags with&nbsp;CSS</a></li><li><a
href='http://davidwalsh.name/mootools-html-police-dwmarkupmarine' rel='bookmark' title='Permanent Link: MooTools HTML Police:&nbsp;dwMarkupMarine'>MooTools HTML Police:&nbsp;dwMarkupMarine</a></li><li><a
href='http://davidwalsh.name/mysqls-replace-phps-strreplace' rel='bookmark' title='Permanent Link: MySQL&#8217;s REPLACE() Is PHP&#8217;s&nbsp;STR_REPLACE()'>MySQL&#8217;s REPLACE() Is PHP&#8217;s&nbsp;STR_REPLACE()</a></li><li><a
href='http://davidwalsh.name/advanced-css-formatting-tags' rel='bookmark' title='Permanent Link: Advanced CSS &#8211; Class Is Out &#8211; Avoiding Classes By Using Formatting Tags For&nbsp;Structure'>Advanced CSS &#8211; Class Is Out &#8211; Avoiding Classes By Using Formatting Tags For&nbsp;Structure</a></li></ol>]]></description> <content:encoded><![CDATA[<p>If you have a website that relies heavily on PRE tags, you know the important of converting PRE tag content to their HTML entities.  Doing so prevents worlds of possible rendering issues.  The following PHP snippet HTML-Entitizes (?) any code within PRE tags:</p><pre class="php">
//replaces pre content with html entities
function pre_entities($matches) {
	return str_replace($matches[1],htmlentities($matches[1]),$matches[0]);
}
//to html entities;  assume content is in the "content" variable
$content = preg_replace_callback('/&lt;pre.*?&gt;(.*?)&lt;\/pre&gt;/imsu',pre_entities, $content);
</pre><p>I use this for just about every post I write.  You could also stick this in your CMS if you have clients that may have use for PRE tags.</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/php-html-entities">Replace Content in PRE Tags with HTML&nbsp;Entities</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/format-code-pre-tags' rel='bookmark' title='Permanent Link: Format Code Inside PRE Tags within TextMate Using&nbsp;PHP'>Format Code Inside PRE Tags within TextMate Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/nobr-css' rel='bookmark' title='Permanent Link: Replace NOBR Tags with&nbsp;CSS'>Replace NOBR Tags with&nbsp;CSS</a></li><li><a
href='http://davidwalsh.name/mootools-html-police-dwmarkupmarine' rel='bookmark' title='Permanent Link: MooTools HTML Police:&nbsp;dwMarkupMarine'>MooTools HTML Police:&nbsp;dwMarkupMarine</a></li><li><a
href='http://davidwalsh.name/mysqls-replace-phps-strreplace' rel='bookmark' title='Permanent Link: MySQL&#8217;s REPLACE() Is PHP&#8217;s&nbsp;STR_REPLACE()'>MySQL&#8217;s REPLACE() Is PHP&#8217;s&nbsp;STR_REPLACE()</a></li><li><a
href='http://davidwalsh.name/advanced-css-formatting-tags' rel='bookmark' title='Permanent Link: Advanced CSS &#8211; Class Is Out &#8211; Avoiding Classes By Using Formatting Tags For&nbsp;Structure'>Advanced CSS &#8211; Class Is Out &#8211; Avoiding Classes By Using Formatting Tags For&nbsp;Structure</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/php-html-entities/feed</wfw:commentRss> <slash:comments>10</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced) (user agent is rejected)
Database Caching 101/303 queries in 3.422 seconds using disk

Served from: davidwalsh.name @ 2010-09-02 23:28:06 -->