Several functions take a
$which parameter. In this section we'll look at two
of these which often work in tandem:
array XML_PullParser_getAttributes (mixed $name, [mixed $which = 1], [array $el = ""])
string XML_PullParser_getText ([mixed $el = ""], [integer $which = 0], [boolean $xcl = false])
As we said in the section on
instantiation ,
the
$child_tags and the
$tags arrays in conjunction with
XML_PullParser_getToken and
XML_PullParser_getElement
act as selectors. The
$which parameter refines the selection.
Where a token contains more than one element of the same name,
$which
specifies which of them is the subject of the query. The elements are stored in the token arrays in document
order, beginning at a
$which value of 1.
The following code will get both the names and the ip addresses of the three servers:
Listing 9
1. $tags = array("entry");
2. $child_tags = array("server","ipaddress", "domain");
3. $parser = new XML_PullParser("DNS.xml",$tags,$child_tags);
4. while($token = $parser->XML_PullParser_getToken())
5. {
6. $parser->XML_PullParser_getElement('server');
7. $which=1;
8. while($server = $parser->XML_PullParser_getText('server',$which)) {
9. $ip = $parser->XML_PullParser_getAttributes('server',$which);
10. echo "Name: $server\n";
11. echo "\tIP: " . $parser->XML_PullParser_getAttrVal('ip', $ip) . "\n";
12. $which++;
13. }
14. }
/*
Result
Name: example_1.com
IP: 192.168.10.1
Name: example_2.com
IP: 192.168.10.2
Name: example_3.com
IP: 192.168.10.3
*/
Listing 9 assumes that we are going to be interested more than just
the servers. So we declare the "entry" element
in the $tags array and the other elements of interest in the $child_tags
array. Line 4 gets the "entry" token and then XML_PullParser_getElement (line 6)
isolates the token's server elements for processing.
Beginning with line 8, the while loop first gets each server's name and then its ipaddress, which
is stored as an attribute of server . The server name is returned as a string and the attribute
as an array, which is passed in to the helper function XML_PullParser_getAttributes,
which then returns the attribute value as a string. The $which value is updated with each turn of the loop
(line 12).