-
Notifications
You must be signed in to change notification settings - Fork 1
/
XmlDomConstruct.class.php
80 lines (71 loc) · 2.13 KB
/
XmlDomConstruct.class.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
<?php
/**
* Extends the DOMDocument to implement personal (utility) methods.
*
* @author Toni Van de Voorde
* http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/
*/
class XmlDomConstruct extends DOMDocument {
/**
* Constructs elements and texts from an array or string.
* The array can contain an element's name in the index part
* and an element's text in the value part.
*
* It can also creates an xml with the same element tagName on the same
* level.
*
* ex:
* <nodes>
* <node>text</node>
* <node>
* <field>hello</field>
* <field>world</field>
* </node>
* </nodes>
*
* Array should then look like:
*
* Array (
* "nodes" => Array (
* "node" => Array (
* 0 => "text"
* 1 => Array (
* "field" => Array (
* 0 => "hello"
* 1 => "world"
* )
* )
* )
* )
* )
*
* @param mixed $mixed An array or string.
*
* @param DOMElement[optional] $domElement Then element
* from where the array will be construct to.
*
*/
public function fromMixed($mixed, DOMElement $domElement = null) {
$domElement = is_null($domElement) ? $this : $domElement;
if (is_array($mixed)) {
foreach( $mixed as $index => $mixedElement ) {
if ( is_int($index) ) {
if ( $index == 0 ) {
$node = $domElement;
} else {
$node = $this->createElement($domElement->tagName);
$domElement->parentNode->appendChild($node);
}
}
else {
$node = $this->createElement($index);
$domElement->appendChild($node);
}
$this->fromMixed($mixedElement, $node);
}
} else {
$domElement->appendChild($this->createTextNode($mixed));
}
}
}
?>