Including Content With PHP
Wednesday, March 10, 2004 at 5:44 pm | Comments off
For all recent sites that I've made, I've used PHP to include the header and footer on each page. Doing this allows me to make a change to one file, and have the entire site respond. For the sake of clarity, a given (static) page on this site would have, until today (more on this later), looked something like this:
<?PHP include $_SERVER['DOCUMENT_ROOT']."/header.php"; ?> <p>Content here</p> <?PHP include $_SERVER['DOCUMENT_ROOT']."/footer.php"; ?>
So basically what I do is split each page where the content begins and ends, and throw it in separate files. This does, however, have on major drawback: each page's header information is the same. For me, the biggest issue with this was the fact that the title remained the same from page to page, when I would rather use a more descriptive title for each page. Why? Well because the title is the most important element on a page, of course. Good titles are very important to SEO.
So, today I decided to deal with this problem. Rather than simply include the headers and footers, I've chosen a new method. I now read the files into a variable, evaluate the string (because I use PHP code in both the header and footer), run a regexp on the title, and echo out my header.
Let's take a look.
<?PHP # grab the files contents (PHP 4.3.0+ with this method) $header_str = file_get_contents($_SERVER['DOCUMENT_ROOT'].» "/header.php"); # get the contents of the header file $header_str = "?>".$header_str."<?php "; # set up the » $header_str. /*We need to prepend the ?> and append the <?PHP because eval() automatically adds tags to the beginning and end. If we do this, it will parse our PHP correctly. */ ob_start(); # turn on output buffering eval($header_str); # evaluate the string as PHP code $output = ob_get_contents(); # return the content of the » output buffer to our $output string ob_end_clean(); # discard the output buffer # do some replacing $output = preg_replace("/<title>(.*?)<\/title>/", "<title>» Ryan Brill | About Ryan Brill</title>", $output); echo $output; # echo our header ?>
This will change from the default title seen on my index page, to a title more appropriate for page describing the designer. The comments should explain what's going on, to those who understand PHP. For those at a beginner level, you simply need to change the top line to point to your included file, and the line after the # do some replacing comment, to change your title.
Obviously, this can be used for many other things. The power is in knowing how to read the contents of a PHP page into a variable, while still parsing the PHP code on that page.
Comments are automatically closed after 45 days