XML.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 $ref;
  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. libxml_disable_entity_loader(true);
  43. return json_decode(
  44. json_encode(
  45. simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)
  46. ),
  47. true
  48. );
  49. }
  50. }