Please visit Straf Spul's main site. This is the nerdy corner.

Unique Random

xml from files in a directory with php

Sometimes people ask me if it is possible to have a dynamic picture slideshow in their website, that requires no other efforts for them other then just uploading the pictures to their webserver. If you want to make it possible that they don't have to be bothered with diving into the code and linking each picture individually to the slideshow, you are gonna have to come up with some script that dynamicly reads out a directory and feeds it to the slideshow.

The following deadsimple php-script looks into a directory and spawns out a valid xml-file of all pictures, that can be loaded by a slideshow (for example the Picturepusher plugin, discussed in another tutorial on this site).

Putting this code in the root of yields the following result for the img folder.

The first line of the script is perhaps the most essential one of the whole script.

header("Content-type: application/xml");

This line tells the application, which loads the contents from the URL of the script, that it should threat the received text as xml rather as just plain text. If you ommit this header your data won't get parsed.

In the $allowed_ext array you can define which file-extensions are allowed to be picked up by the script. Every definition should consist out of exactly four characters, since the check is being done by getting the last four characters of the filename with substr. If the desired extension is only three characters long, you can begin with a dot.

The function opendir creates a handle for the directory and then the function readdir returns the directory listing. If the filename is not a directory itself and it's extension is allowed, the path to the file is wrapped in a tag and added to the xml-file.

Quinten Clause