1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Guillermoandrae\Highrise\Helpers; |
4
|
|
|
|
5
|
|
|
use Guillermoandrae\Common\Collection; |
6
|
|
|
use Guillermoandrae\Common\CollectionInterface; |
7
|
|
|
use SimpleXMLElement; |
8
|
|
|
|
9
|
|
|
final class Xml |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Converts a one-dimensional associative array to an XML string using the |
13
|
|
|
* provided data. |
14
|
|
|
* |
15
|
|
|
* @param string $root The name of the root element. |
16
|
|
|
* @param array $data The XML data. |
17
|
|
|
* @return string |
18
|
|
|
*/ |
19
|
3 |
|
public static function toXml(string $root, array $data) |
20
|
|
|
{ |
21
|
3 |
|
$body = sprintf('<%s>', $root); |
22
|
3 |
|
foreach ($data as $key => $value) { |
23
|
3 |
|
$body .= sprintf('<%s>%s</%s>', $key, $value, $key); |
24
|
|
|
} |
25
|
3 |
|
$body .= sprintf('</%s>', $root); |
26
|
3 |
|
return $body; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Converts an XML string into either an associative array or an array of |
31
|
|
|
* associative arrays. |
32
|
|
|
* |
33
|
|
|
* @param string $xml The XML string. |
34
|
|
|
* @return array|CollectionInterface |
35
|
|
|
*/ |
36
|
20 |
|
public static function fromXml(string $xml) |
37
|
|
|
{ |
38
|
20 |
|
libxml_use_internal_errors(true); |
39
|
20 |
|
if (!$obj = simplexml_load_string($xml)) { |
40
|
1 |
|
return []; |
41
|
|
|
} |
42
|
19 |
|
if ($obj->attributes()) { |
43
|
12 |
|
$items = []; |
44
|
12 |
|
foreach ($obj->children() as $child) { |
45
|
12 |
|
$items[] = static::flatten($child); |
46
|
|
|
} |
47
|
12 |
|
return Collection::make($items); |
48
|
|
|
} |
49
|
7 |
|
return (array) static::flatten($obj); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Removes attributes from SimpleXMLElement objects. |
54
|
|
|
* |
55
|
|
|
* @param SimpleXMLElement $item The SimpleXMLElement object. |
56
|
|
|
* @return array |
57
|
|
|
*/ |
58
|
19 |
|
public static function flatten(SimpleXMLElement $item) |
59
|
|
|
{ |
60
|
19 |
|
$parsedItem = []; |
61
|
19 |
|
foreach ($item as $key => $value) { |
62
|
18 |
|
$parsedItem[$key] = (string) $value; |
63
|
|
|
} |
64
|
19 |
|
return $parsedItem; |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|