XML_PullParser
A token-based interface to the PHP expat XML library
version 1.3.2
Myron Turner
Introduction to Coding I: CDATA

Contents         

The aim of this section and the next is to give readers a feel for how XML_PullParser works. The code listings are fragments and cannot stand alone. Later sections will show the contexts that make them functional.

Example 1
<ENTRY> 
<ipaddress> 172.20.19.6 </ipaddress> 
<domain> example.com </domain> 
<server ip="192.168.10.1"> example_1.com </server> 
<server ip="192.168.10.2"> example_2.com </server> 
<server ip="192.168.10.3"> example_3.com </server> 
<alias> <www.example.com </alias> 
</ENTRY> 

<ENTRY> 
<ipaddress> 172.20.19.7 </ipaddress> 
        •
        •
<alias> <www.example.org </alias> 
</ENTRY> 

There are five pieces of data that can be extracted from <ENTRY> . These are ipaddress, domain, server, server ip, and alias. Getting the IP address involves three lines of code.

Listing 1
	   1.   while($token = $parser->XML_PullParser_getToken())
	   2.   { 
	   3.       $ipaddress=$parser->XML_PullParser_getElement('ipaddress');       
	   4.       echo "IP Adress: " . $parser->XML_PullParser_getText() ."\n";
	   5.   }
                    
    /*  Result
        IP Adress: 172.20.19.6
        IP Adress: 172.20.19.7
    */	         
	

With each turn of the loop, an ENTRY structure is returned by XML_PullParser_getToken, which must always be called before taking any other action: It gets gets the next token from the token stack and sets up the basis for all the other tokenizing functions.

In line 3 the ipaddress element is declared as the object of whatever happens next. In this case, it's a call to XML_PullParser_getText, which returns the IP adress as a string. The same coding could be used for both domain and alias. Getting the server names requires one additonal line of code.

Listing 2
       1.   while($token = $parser->XML_PullParser_getToken())
       2.   { 
       3.       $dns_servers=$parser->XML_PullParser_getElement('server');    
       4.       while($server = $parser->XML_PullParser_nextElement()) 
       5.       {        
       6.           echo "Server: " . $parser->XML_PullParser_getText($server) ."\n";
       7.       }
       8.   }
    /*  Result
        Server: ns1.example.net
        Server: ns2.example.net
        Server: ns3.example.net
    */	         
	

Again, XML_PullParser_getElement picks out the element of interest. Line 4 contains the new code, XML_PullParser_nextElement , which returns the server elements in the same order in which they appear in the XML document. XML_PullParser_getText (line 6) then returns the text from each of the server elements. There are other ways to do this job, and we'll look at them, but this is the most intuitive and elegant.