Helping ordinary people create extraordinary websites!

Parsing XML using PHP4

By Burhan Khalid
2005-08-16

Starting up the parser

Now that the parser is setup and configured, we are ready to feed it our XML file and let it parse the information. This is the complicated part of the program, so extra attention is requested.

The first step is to open the xml file :

PHP:

  1. $filename = "sample.xml";
  2. if (!($fp = fopen($filename, "r"))) { die("cannot open ".$filename); }

This simple code will check to see if our program can open the file or not. It will quit with an appropriate message if it cannot.

Once the file is open, we must read it and feed it to the XML parser. One thing we are going to do before we send the file to the XML parser is we are going to get rid of any whitespace using a regular expression and the eregi_replace function :

PHP:

  1. while ($data = fread($fp, 4096)){
  2.    $data=eregi_replace(">"."[[:space:]]+"."< ",">< ",$data);
  3.    if (!xml_parse($xmlparser, $data, feof($fp))) {
  4.       $reason = xml_error_string(xml_get_error_code($xmlparser));
  5.       $reason .= xml_get_current_line_number($xmlparser);
  6.       die($reason);
  7.    }
  8. }
  9. xml_parser_free($xmlparser);

Lets step through this code :

  1. The fread() function reads the data from the xml file (given by the $fp handle), and stores it in $data.
  2. We use the eregi_replace function to get rid of the whitespace in $data
  3. We then check to see if the data was parsed or not, if it isn’t, we use the built-in xml error reporting functions to print out an informative error message.
  4. At the end, we free the parser (destory it)

Once we have verified that our parser is working properly, we are ready to actually do something with the data.





Tutorial pages:

© 2004-2005 Burhan Khalid


 2 Votes

You might also want to check these out:


Leave a Comment on "Parsing XML using PHP4"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS