-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsimplexml-iterator.php
112 lines (102 loc) · 2.67 KB
/
simplexml-iterator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
* This example demonstrates recursively iterating over an XML file
* to any particular path.
*/
$xmlstring = <<<XML
<?xml version = "1.0" encoding="UTF-8" standalone="yes"?>
<document>
<animal>
<category id="26">
<species>Phascolarctidae</species>
<type>koala</type>
<name>Bruce</name>
</category>
</animal>
<animal>
<category id="27">
<species>macropod</species>
<type>kangaroo</type>
<name>Bruce</name>
</category>
</animal>
<animal>
<category id="28">
<species>diprotodon</species>
<type>wombat</type>
<name>Bruce</name>
</category>
</animal>
<animal>
<category id="31">
<species>macropod</species>
<type>wallaby</type>
<name>Bruce</name>
</category>
</animal>
<animal>
<category id="21">
<species>dromaius</species>
<type>emu</type>
<name>Bruce</name>
</category>
</animal>
<animal>
<category id="22">
<species>Apteryx</species>
<type>kiwi</type>
<name>Troy</name>
</category>
</animal>
<animal>
<category id="23">
<species>kingfisher</species>
<type>kookaburra</type>
<name>Bruce</name>
</category>
</animal>
<animal>
<category id="48">
<species>monotremes</species>
<type>platypus</type>
<name>Bruce</name>
</category>
</animal>
<animal>
<category id="4">
<species>arachnid</species>
<type>funnel web</type>
<name>Bruce</name>
<legs>8</legs>
</category>
</animal>
</document>
XML;
try {
// load the XML Iterator and iterate over it
$sxi = new SimpleXMLIterator($xmlstring);
// iterate over animals
foreach ($sxi as $animal) {
// iterate over category nodes
foreach ($animal as $key => $category) {
echo $category->species . PHP_EOL;
}
}
} catch(Exception $e) {
die($e->getMessage());
}
echo '===================================' . PHP_EOL;
echo 'Finding all species with xpath' . PHP_EOL;
echo '===================================' . PHP_EOL;
// which can also be re-written for optimization
try {
// load the XML Iterator and iterate over it
$sxi = new SimpleXMLIterator($xmlstring);
// use xpath
$foo = $sxi->xpath('animal/category/species');
foreach ($foo as $k => $v) {
echo $v . PHP_EOL;
}
} catch(Exception $e) {
die($e->getMessage());
}