Repository navigation
Expand file tree
/
Copy pathXml.php
More file actions
61 lines (54 loc) · 1.69 KB
/
Copy pathXml.php
File metadata and controls
61 lines (54 loc) · 1.69 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
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact [email protected]
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Codec;
use Hyperf\Codec\Exception\InvalidArgumentException;
use Hyperf\Contract\Arrayable;
use Hyperf\Contract\Xmlable;
use SimpleXMLElement;
class Xml
{
public static function toXml(mixed $data, ?SimpleXMLElement $parentNode = null, string $root = 'root')
{
if ($data instanceof Xmlable) {
return (string) $data;
}
if ($data instanceof Arrayable) {
$data = $data->toArray();
} else {
$data = (array) $data;
}
if ($parentNode === null) {
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?>' . "<{$root}></{$root}>");
} else {
$xml = $parentNode;
}
foreach ($data as $key => $value) {
if (is_array($value)) {
self::toXml($value, $xml->addChild($key));
} else {
if (is_numeric($key)) {
$xml->addChild('item' . $key, (string) $value);
} else {
$xml->addChild($key, (string) $value);
}
}
}
return trim($xml->asXML());
}
public static function toArray($xml): array
{
$respObject = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR);
if ($respObject === false) {
throw new InvalidArgumentException('Syntax error.');
}
return json_decode(json_encode($respObject), true);
}
}