If you find this useful, you might like my other articles, too.

There are a lot of good articles available about how to customize the layout of you blog but sometimes want to add some kind of outside information to your blog. For complex or large amounts of information, you should consider a database solution but in a lot of cases a simple file based solution works, too. This tutorial shows you how to add information from a file to your blog.

Recently I added a “Just read” block to my sidebar containing links and images to the books I have read and a rating. At first this was a static html block, just to see how it will look. Lazy as I am, I didn’t want to write html every time I finish a book. This is why I moved the information from the sidebar.php into a seperate file called books.txt in the main directory of my blog.

The file

The file contains 5 tab seperated columns for author, title, amazon url, amazon image url and url for the rating image. A sample line looks like this:


Reading and parsing the file is pretty easy in php (this is taken directly from the php manual):

$lines = file('books.txt');
foreach ($lines as $line_num => $line) {
  $parsed = explode("\t", rtrim($line));
  ...
}

As I wanted only the first 4 books to show, I added a check to echo only the lines with a line number less than 4. rtrim removes the whitespaces/newlines from the end of the line and explode splits the line at every tab. This leaves me with an array of 5 strings. The final step of assembling an entry for a book within a <td> is straightforward. After every 2 books a </tr><tr> is added to create a 2×2 block of books.

Here’s the whole block, as it is used in my sidebar, if you have any questions feel free to ask…



Any comments? Or questions? Just leave a Reply: