|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace leandrogehlen\exporter\serializers; |
|
4
|
|
|
|
|
5
|
|
|
use DOMDocument; |
|
6
|
|
|
use DOMElement; |
|
7
|
|
|
use DOMText; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Formats the given data into XML content. |
|
11
|
|
|
* |
|
12
|
|
|
* @author Leandro Guindani Gehlen <[email protected]> |
|
13
|
|
|
*/ |
|
14
|
|
|
class XmlSerializer extends HierarchicalSerializer |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var string the XML version |
|
18
|
|
|
*/ |
|
19
|
|
|
public $version = '1.0'; |
|
20
|
|
|
/** |
|
21
|
|
|
* @var string the XML encoding. |
|
22
|
|
|
*/ |
|
23
|
|
|
public $encoding = 'UTF-8'; |
|
24
|
|
|
/** |
|
25
|
|
|
* @var string the name of the root element. |
|
26
|
|
|
*/ |
|
27
|
|
|
public $rootTag = 'items'; |
|
28
|
|
|
/** |
|
29
|
|
|
* @var string the name of the elements that represent the array elements with numeric keys. |
|
30
|
|
|
*/ |
|
31
|
|
|
public $itemTag = 'item'; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @inheritdoc |
|
35
|
|
|
*/ |
|
36
|
1 |
|
public function formatData($data) |
|
37
|
|
|
{ |
|
38
|
1 |
|
$dom = new DOMDocument($this->version, $this->encoding); |
|
39
|
|
|
|
|
40
|
1 |
|
if (count($this->exporter->sessions) === 1) { |
|
41
|
1 |
|
$root = $dom; |
|
42
|
1 |
|
} else { |
|
43
|
1 |
|
$root = new DOMElement($this->rootTag); |
|
44
|
1 |
|
$dom->appendChild($root); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
1 |
|
$this->buildXml($root, $data); |
|
48
|
1 |
|
return $dom->saveXML(); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* @param \DOMNode $element |
|
53
|
|
|
* @param mixed $data |
|
54
|
|
|
*/ |
|
55
|
1 |
|
protected function buildXml($element, $data) |
|
56
|
|
|
{ |
|
57
|
1 |
|
foreach ($data as $name => $value) { |
|
58
|
1 |
|
if (is_int($name) && is_object($value)) { |
|
59
|
|
|
$this->buildXml($element, $value); |
|
60
|
1 |
|
} elseif (is_array($value)) { |
|
61
|
1 |
|
$child = new DOMElement(is_int($name) ? $this->itemTag : $name); |
|
62
|
1 |
|
$element->appendChild($child); |
|
63
|
1 |
|
$this->buildXml($child, $value); |
|
64
|
1 |
|
} else { |
|
65
|
1 |
|
$child = new DOMElement(is_int($name) ? $this->itemTag : $name); |
|
66
|
1 |
|
$element->appendChild($child); |
|
67
|
1 |
|
$child->appendChild(new DOMText((string)$value)); |
|
68
|
|
|
} |
|
69
|
1 |
|
} |
|
70
|
1 |
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|