Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

Parsing XML using PHP4

By Burhan Khalid
2005-08-16


Creating the gallery

Now that we have verified that our parser works, we are ready to modify our parser to actually make use of our information. In order to do this, we only have to deal with our custom functions that handle the data.

Lets print out a nice little gallery using our images. Our gallery will just print the image with its dimentions, and a caption that is the name of the image. I will type out the modified functions, and then explain the code :

PHP:

  1. $current = "";
  2. function start_tag($parser, $name, $attribs) {
  3.    global $current;
  4.    $current = $name;
  5.    if ($name == "IMAGEINFO") { echo "<table border=\"1\" width=\"50%\">"; }
  6.    if ($name == "IMAGE") { echo "<tr><td>"; }
  7.    if ($name == "FILENAME") { echo "<img src=\""; }
  8.    if ($name == "NAME") { echo "</div/></td></tr><tr><td><div align=\"center\">"; }
  9.    if ($name == "SIZE") {
  10.    if (is_array($attribs)) {
  11.       while(list($key,$val) = each($attribs)) {
  12. echo strtolower($key)."=\"".$val."\"";
  13.       }
  14.    }
  15. }
  16. function end_tag($parser, $name) {
  17.    if ($name == "NAME") { echo "</div></td></tr>"; }
  18.    if ($name == "FILENAME") { echo " />"; }
  19.    if ($name == "IMAGEINFO") { echo "</table>"; }
  20. }
  21. function tag_contents($parser, $data) {
  22.    global $current;
  23.    if ($current == "FILENAME") { echo $data; }
  24.    if ($current == "NAME") { echo $data; }
  25. }

Since the tag_contents() functions doesn’t get the name of the current tag from the parser, we have to manually provide it that information. In our start_tag() function, we set a global variable $current to the current tag name. The rest of the code is just checks to see which tag we are on, and print out the appropriate tags.

That's it! Now you have a "skeleton" parser that you can modify to use with XML files (such as RSS feeds).

Notes

You'll note that I am comparing tag names in upper case. The parser by default converts all tags to upper case. This behavior can be changed by passing arguments to the xml_parser_create() function.



Tutorial Pages:
» Parsing XML using PHP4
» XML File Structure
» Creating our XML File
» Parsing with PHP
» Creating our Parser
» Setting up tag handlers
» Setting up content (data) handlers
» Starting up the parser
» Creating the gallery


© 2004-2005 Burhan Khalid


 | Bookmark
Related Tutorials:
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1
» Desktop Application Development with PHP-GTK

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources