Menu

[r27]: / branches / parse_tree / XML2Array.php  Maximize  Restore  History

Download this file

73 lines (66 with data), 1.8 kB

 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
<?php
/**
* Class to convert a DOMNode into an Array
*/
class XML2Array {
/**
* @var DOMNode
*/
protected $node;
public function __construct(DOMNode $node) {
$this->node = $node;
}
/**
* @return array
*/
public function getArray() {
$array = array();
$array[$this->node->nodeName] = $this->toArray($this->node);
return $array;
}
/**
* @return array|string
*/
protected function toArray(DOMNode $node) {
$array = array();
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType == XML_TEXT_NODE) {
$text = trim($childNode->nodeValue);
if (strlen($text) > 0) { // skip pure whitespace text nodes
$array[] = $text;
}
} else {
$array[$childNode->localName] = $this->toArray($childNode);
}
}
}
return $array;
}
/**
* @return string the array as PHP code
*/
public function __toString() {
$string = $this->arrayToString($this->getArray());
return $string;
}
/**
* @param integer $level
* @return string
*/
public static function arrayToString(Array $array, $level = 0) {
$string = '';
foreach ($array as $key => $value) {
$string.= str_repeat(' ', $level);
if (is_array($value)) {
$string.= $key;
$string.= "\n";
$string.= self::arrayToString($value, $level + 1);
} else {
$string.= '"' . $value . "\"\n";
}
}
return $string;
}
}
?>