How to Pre-Parse a PHP Include

November 17, 2007Stephen Ward

I’ve been coding in PHP for more than five years now and I’m still learning new tricks. A novel problem the other day led me to learn how to pre-parse a PHP file prior to inclusion.

Here was my problem. My friend Adam asked me to write some code to include recent post lists outside of WordPress on a client’s site. For those who know a thing or two about WordPress, this wouldn’t normally be an issue; just use the following two lines of code and you’re all set to make use of built-in WordPress functions:

<?php
define('WP_USE_THEMES', false);
require_once('/path/to/wp-blog-header.php');
?>

Unfortunately, the site he wanted me to do this on used Smarty templates. Now, I’ve heard good things about Smarty, but I know less than jack about using it. After spinning my wheels for awhile, I finally discovered that I couldn’t include WordPress in Smarty templates without generating fatal errors.

As you might have guessed from the title of this post, my solution to this was to separate the WordPress code into an external PHP file and include it as pre-parsed output. To do this, simply set allow_url_fopen to true (either in php.ini or through the ini_set() function). Then, include the output file using its http path rather than its file path. Here’s the code I used:

<?php
ini_set('allow_url_fopen', 1);
echo file_get_contents('http://www.domain.com/path/to/file.php');
?>

The result is that you get the raw output of the file without the code, completely separating it from the normal flow of execution. It becomes more like reading a text file. In my case, it allowed me to create dynamic WordPress post lists from within an active Smarty template file. I don’t know about you, but I’ll be filing that one under “handy tricks” in my PHP handbook. ;)

CommentBookmark Subscribe
On May 1, 2008, Binny V A wrote the following comment:

There is another way - Capture the Output of an Included File in PHP. I am not sure whether it will work in your context - but this is something I use.

On May 1, 2008, Stephen Ward wrote the following comment:

Thanks for the tip, Binny. However, it looks like your code includes the file and parses it normally, in which case it would have blown up in my example. Still, it’s a neat way to use output buffering to pull the output into a variable.

Name
Email Address
Website URL

« Previous Entry Building a Better Website Next Entry »