XML.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace AlibabaCloud\Tea\XML;
  3. class XML
  4. {
  5. public static function parseXml($xmlStr, $response)
  6. {
  7. $res = self::parse($xmlStr);
  8. if ($response === null) {
  9. return $res;
  10. } else {
  11. if (\is_string($response)) {
  12. $response = new $response();
  13. }
  14. $prop = get_object_vars($response);
  15. $target = [];
  16. foreach ($res as $k => $v) {
  17. if (isset($prop[$k])) {
  18. $target[$k] = $v;
  19. }
  20. }
  21. return $target;
  22. }
  23. }
  24. public static function toXML($array)
  25. {
  26. $arrayToXml = new ArrayToXml();
  27. if (\is_object($array)) {
  28. $tmp = explode('\\', \get_class($array));
  29. $rootName = $tmp[\count($tmp) - 1];
  30. $data = json_decode(json_encode($array), true);
  31. } else {
  32. $tmp = $array;
  33. reset($tmp);
  34. $rootName = key($tmp);
  35. $data = $array[$rootName];
  36. }
  37. ksort($data);
  38. return $arrayToXml->buildXML($data, $rootName);
  39. }
  40. private static function parse($xml)
  41. {
  42. if (\PHP_VERSION_ID < 80000) {
  43. libxml_disable_entity_loader(true);
  44. }
  45. return json_decode(
  46. json_encode(
  47. simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)
  48. ),
  49. true
  50. );
  51. }
  52. }