Parsing XML using PHP4
By Burhan Khalid2005-08-16
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:
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:
- while ($data = fread($fp, 4096)){
- $data=eregi_replace(">"."[[:space:]]+"."< ",">< ",$data);
- if (!xml_parse($xmlparser, $data, feof($fp))) {
- $reason = xml_error_string(xml_get_error_code($xmlparser));
- $reason .= xml_get_current_line_number($xmlparser);
- die($reason);
- }
- }
- xml_parser_free($xmlparser);
Lets step through this code :
- The fread() function reads the data from the xml file (given by the $fp handle), and stores it in $data.
- We use the eregi_replace function to get rid of the whitespace in $data
- 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.
- 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
|
|||||||||
You might also want to check these out:
|
Link to This Tutorial Page!

