| 1 |
lars |
1 |
<?PHP
|
|
|
2 |
/**
|
|
|
3 |
* This example shows different methods how
|
|
|
4 |
* XML_Unserializer can be used to create data structures
|
|
|
5 |
* from XML documents.
|
|
|
6 |
*
|
|
|
7 |
* @author Stephan Schmidt <schst@php.net>
|
|
|
8 |
*/
|
|
|
9 |
error_reporting(E_ALL);
|
|
|
10 |
|
|
|
11 |
// this is a simple XML document
|
|
|
12 |
$xml = '<users>' .
|
|
|
13 |
' <user handle="schst">Stephan Schmidt</user>' .
|
|
|
14 |
' <user handle="mj">Martin Jansen</user>' .
|
|
|
15 |
' <group name="qa">PEAR QA Team</group>' .
|
|
|
16 |
' <foo id="test">This is handled by the default keyAttribute</foo>' .
|
|
|
17 |
' <foo id="test2">Another foo tag</foo>' .
|
|
|
18 |
'</users>';
|
|
|
19 |
|
|
|
20 |
require_once 'XML/Unserializer.php';
|
|
|
21 |
|
|
|
22 |
// complex structures are arrays, the key is the attribute 'handle' or 'name', if handle is not present
|
|
|
23 |
$options = array(
|
|
|
24 |
XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'array',
|
|
|
25 |
XML_UNSERIALIZER_OPTION_ATTRIBUTE_KEY => array(
|
|
|
26 |
'user' => 'handle',
|
|
|
27 |
'group' => 'name',
|
|
|
28 |
'#default' => 'id'
|
|
|
29 |
)
|
|
|
30 |
);
|
|
|
31 |
|
|
|
32 |
// be careful to always use the ampersand in front of the new operator
|
|
|
33 |
$unserializer = &new XML_Unserializer($options);
|
|
|
34 |
|
|
|
35 |
// userialize the document
|
|
|
36 |
$status = $unserializer->unserialize($xml, false);
|
|
|
37 |
|
|
|
38 |
if (PEAR::isError($status)) {
|
|
|
39 |
echo 'Error: ' . $status->getMessage();
|
|
|
40 |
} else {
|
|
|
41 |
$data = $unserializer->getUnserializedData();
|
|
|
42 |
echo '<pre>';
|
|
|
43 |
print_r($data);
|
|
|
44 |
echo '</pre>';
|
|
|
45 |
}
|
|
|
46 |
|
|
|
47 |
|
|
|
48 |
// unserialize it again and change the complexType option
|
|
|
49 |
// but leave other options untouched
|
|
|
50 |
// now complex types will be an object, and the property name will be in the
|
|
|
51 |
// attribute 'handle'
|
|
|
52 |
$status = $unserializer->unserialize($xml, false, array(XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'object'));
|
|
|
53 |
|
|
|
54 |
if (PEAR::isError($status)) {
|
|
|
55 |
echo 'Error: ' . $status->getMessage();
|
|
|
56 |
} else {
|
|
|
57 |
$data = $unserializer->getUnserializedData();
|
|
|
58 |
echo '<pre>';
|
|
|
59 |
print_r($data);
|
|
|
60 |
echo '</pre>';
|
|
|
61 |
}
|
|
|
62 |
|
|
|
63 |
// unserialize it again and change the complexType option
|
|
|
64 |
// and reset all other options
|
|
|
65 |
// Now, there's no key so the tags are stored in an array
|
|
|
66 |
$status = $unserializer->unserialize($xml, false, array(XML_UNSERIALIZER_OPTION_OVERRIDE_OPTIONS => true, XML_UNSERIALIZER_OPTION_COMPLEXTYPE => 'object'));
|
|
|
67 |
|
|
|
68 |
if (PEAR::isError($status)) {
|
|
|
69 |
echo 'Error: ' . $status->getMessage();
|
|
|
70 |
} else {
|
|
|
71 |
$data = $unserializer->getUnserializedData();
|
|
|
72 |
echo '<pre>';
|
|
|
73 |
print_r($data);
|
|
|
74 |
echo '</pre>';
|
|
|
75 |
}
|
|
|
76 |
?>
|