1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace FinanCalc\Utils\Serializers { |
4
|
|
|
|
5
|
|
|
use FinanCalc\Interfaces\Serializer\SerializerInterface; |
6
|
|
|
use FinanCalc\Utils\Config; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class XMLSerializer |
10
|
|
|
* @package FinanCalc\Utils\Serializers |
11
|
|
|
*/ |
12
|
|
|
class XMLSerializer implements SerializerInterface |
13
|
|
|
{ |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param array $inputArray |
17
|
|
|
* @return mixed |
18
|
|
|
* |
19
|
|
|
* inspired by http://stackoverflow.com/questions/9152176/convert-an-array-to-xml-or-json |
20
|
|
|
*/ |
21
|
|
|
public static function serializeArray(array $inputArray) |
22
|
|
|
{ |
23
|
|
|
$domDocument = new \DOMDocument('1.0', 'UTF-8'); |
24
|
|
|
$domDocument->formatOutput = true; |
25
|
|
|
|
26
|
|
|
$rootElem = $domDocument->createElement( |
27
|
|
|
Config::getConfigField('serializers_root_elem_name') |
28
|
|
|
); |
29
|
|
|
$domDocument->appendChild($rootElem); |
30
|
|
|
|
31
|
|
|
$funcArrayToXML = |
32
|
|
|
function (\DOMElement $parentNode, $inputArray) |
33
|
|
|
use ($domDocument, &$funcArrayToXML) { |
34
|
|
|
foreach ($inputArray as $key => $value) { |
35
|
|
|
$key = preg_replace('/(^[0-9])/', '_\1', str_replace(' ', '_', $key)); |
36
|
|
|
$isValueArray = is_array($value); |
37
|
|
|
|
38
|
|
|
$elem = $domDocument->createElement($key, (!$isValueArray) ? $value : null); |
39
|
|
|
$parentNode->appendChild($elem); |
40
|
|
|
|
41
|
|
|
if ($isValueArray) { |
42
|
|
|
$funcArrayToXML($elem, $value); |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
}; |
46
|
|
|
|
47
|
|
|
$funcArrayToXML($rootElem, $inputArray); |
48
|
|
|
|
49
|
|
|
return $domDocument->saveXML(); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|