Each XML file can have it’s own DTD or structure. The PHP file using the XML parser must be tailored to one particular structure or DTD – it will then be able to read all files that are valid under that DTD. This example will use an over-simplified contacts format for XML – you will need to adapt the details of the tags (or nodes) for your own DTD. To follow the construction of the XML parser, load the example XML file into another window using the link in the Navigation Bar. (If the file doesn’t open in a new window in your browser, right click the link and choose Open in a New Window.) Multiple contacts can be specified by repeating the CONTACT tag and the PHP file therefore needs to keep track of the number of contacts used in this example. In the above code, $usercount is set to zero ready to hold the number of contacts found. $userdata will later be filled with data for each contact and $state is used to keep track of which node the parser is dealing with for each contact.

The PHP XML parser now needs two functions to be declared, one to handle the element data and one to handle the character data within the elements. This is where you need to change the code to reflect your own XML files – change the element and attribute names. I’ll start with the Element Handler. This is in two parts, a function to detect the start of real data and a function to detect when an element comes to an end – in this case to register when more than one contact is specified. Each function is called once for each node – use a switch statement to decide what action to take depending on which node is being processed. The parser will take care of the $name and $attrib variables.