Friday 19 February 2010

Build a menu bar on-the-fly with JavaScript

Its not necessary to use either PHP or SHTML to include a dynamic menubar in a set of web pages - you can do it with JavaScript.

First define arrays containing all the links and the link text you want for the links - make certain the two arrays have the same number of elements!

Then have a loop that goes through these arrays, displaying them on the screen in order. You can do a bit of string testing to work out what page you're on and have that link displayed differently - perhaps in bold or just not underlined. Output all the HTML using document.write

Here's an example:

var textArray=new Array('home','news','people','places','views', 'faq');
var linksArray=new Array('index.html','news.html','people.html','places.html','views.html','faq.html');

for (i=0;i < textArray.length; i++) {
var str = window.location.toString();
var urlbits = str.split('/');
if (urlbits[urlbits.length-1]!=linksArray[i]) {
document.write(''+textArray[i]+'');
} else {
document.write(''+textArray[i]+'');
}
if (i!=textArray.length-1) document.write(' | ');
}

Note how the last line in the loop misses off the delimiter for the last item.

Save this JavaScript in a separate file - something like menubar.js - and include it in the same place in all of your HTML pages using a conventional link to an external JavaScript file:

<script type="text/javascript" src="menubar.js"></script>

My links here are just straightforward links, but they could equally be styled bullet list items, buttons, images, whatever.

Thursday 18 February 2010

Parsing RSS with Dubin Core using PHP5

With the built-in XML functions of PHP5, its now pretty straightforward to parse well-formed RSS data, eg:

$link = $node->getElementsByTagName('link')->item(0)->nodeValue;

But when using getElementsByName you run into problems if you want to grab data in Dublin Core fields - this won't work:

$creator = $node->getElementsByTagName('dc:creator')->item(0)->nodeValue;

To solve this you have to use the getElementsByTagNameNS function and declare the namespace you are using - obviously in this case Dublin Core:

$creator = $node->getElementsByTagNameNS('http://purl.org/dc/elements/1.1/','creator')->item(0)->nodeValue;