Xml.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Codec;
  12. use Hyperf\Codec\Exception\InvalidArgumentException;
  13. use Hyperf\Contract\Arrayable;
  14. use Hyperf\Contract\Xmlable;
  15. use SimpleXMLElement;
  16. class Xml
  17. {
  18. public static function toXml(mixed $data, ?SimpleXMLElement $parentNode = null, string $root = 'root')
  19. {
  20. if ($data instanceof Xmlable) {
  21. return (string) $data;
  22. }
  23. if ($data instanceof Arrayable) {
  24. $data = $data->toArray();
  25. } else {
  26. $data = (array) $data;
  27. }
  28. if ($parentNode === null) {
  29. $xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?>' . "<{$root}></{$root}>");
  30. } else {
  31. $xml = $parentNode;
  32. }
  33. foreach ($data as $key => $value) {
  34. if (is_array($value)) {
  35. self::toXml($value, $xml->addChild($key));
  36. } else {
  37. if (is_numeric($key)) {
  38. $xml->addChild('item' . $key, (string) $value);
  39. } else {
  40. $xml->addChild($key, (string) $value);
  41. }
  42. }
  43. }
  44. return trim($xml->asXML());
  45. }
  46. public static function toArray($xml): array
  47. {
  48. $respObject = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR);
  49. if ($respObject === false) {
  50. throw new InvalidArgumentException('Syntax error.');
  51. }
  52. return json_decode(json_encode($respObject), true);
  53. }
  54. }