XML_PullParser
A token-based interface to the PHP expat XML library
version 1.3.2
Myron Turner
Introduction to Coding 2: Adding Attributes

Contents         

The previous section dealt with extracting character data from XML tags. Still using Example 1 from that section, we'll look at extracting the ip attributes from the server elements.

Listing 3
  1.   while($token = $parser->XML_PullParser_getToken())
  2.   {
  3.       $parser->XML_PullParser_getElement('server');    
  4.       while($server = $parser->XML_PullParser_nextElement()) 
  5.       {        
  6.           $attr_array = $parser->XML_PullParser_getAttributes($server);
  7.           $ip = $parser->XML_PullParser_getAttrVal("ip",$attr_array);
  8.           echo "Server IP: $ip\n";  
  9.       }
 10.      echo "\n";
 11.   }

/* Result 
    Server IP: 192.168.0.1
    Server IP: 192.168.0.2
    Server IP: 192.168.0.3
    Server IP: 192.168.0.4

    Server IP: 192.168.0.5
*/

What's new here are lines 6 and 7. XML_PullParser_getAttributes takes a $server object and returns an associative array of attribute names and values for each server. This array could be addressed in the usual manner:

$ip = $attr_array['ip'].

This is exactly what XML_PullParser_getAttrVal does, with one difference: it converts the index term to upper case if case-folding is in effect, which is the default for the PHP XML parser.

What follows is a small routine that puts together attribute handling with getting the character data from elements.

Listing 4
 1.    while($token = $parser->XML_PullParser_getToken())
 2.    { 
 3.
 4.        $parser->XML_PullParser_getElement('server');    
 5.
 6.        while($server = $parser->XML_PullParser_nextElement()) 
 7.        {        
 8.            echo "Server Name: " . $parser->XML_PullParser_getText($server) ."\n";  
 9.            $attr_array = $parser->XML_PullParser_getAttributes($server);
10.            $ip = $parser->XML_PullParser_getAttrVal("ip",$attr_array);
11.            echo "Server IP: $ip\n";              
12.        }
13.    }

/* Result 

    Server Name: example_1.com
    Server IP: 192.168.10.1
    Server Name: example_2.com
    Server IP: 192.168.10.2
    Server Name: example_3.com
    Server IP: 192.168.10.3
*/

Everything here is familiar. It's Listing 3 with the addition of line 8, which calls XML_PullParser_getText , a function introduced in Listing 2 of the previous section.

The next section will look at at how to create the XML_PullParser object.