Creating our Parser
The first step is to create and setup our parser. The xml_parser_create() function will create the parser for us, and return us a handle to that parser. We will then have to setup the different handlers so that the parser knows what to do with each type of information (be it an opening tag, a closing tag, stuff between the tag, etc). Lets first check to make sure that we can create our parser, which is perhaps the least confusing line of code :
if (! ($xmlparser = xml_parser_create()) )
{
die ("Cannot create parser");
}
This code simply checks to see if we can create a parser. It will quit with an appropriate message, since if we can’t create the parser, there is no use in going any further. If your script quits here with the error message, then your PHP installation isn’t setup with the expat library. Most Unix/Linux based servers have the expat library as part of their PHP install. Check the xml reference section of the PHP manual for instructions on installing the expat library. Alternately, you can also send a support request to your host/ISP’s help desk.
Once we have created our parser, it is time to configure it to handle our XML file. The xml_set_element_handler() function takes three arguments. The first one is a handle to our xml_parser (which is $xmlparser). The next argument is the name of a function that the parser will call when it finds an open tag, and the last argument is the name of a function that the parser will call when it reaches an ending tag. We are going to write the functions that will be called for each open and close tag. Sounds scary, but it really is very straightforward.