Xml.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Convert;
  7. /**
  8. * Convert xml data (SimpleXMLElement object) to array
  9. */
  10. class Xml
  11. {
  12. /**
  13. * Transform \SimpleXMLElement to associative array
  14. * \SimpleXMLElement must be conform structure, generated by assocToXml()
  15. *
  16. * @param \SimpleXMLElement $xml
  17. * @return array
  18. */
  19. public function xmlToAssoc(\SimpleXMLElement $xml)
  20. {
  21. $array = [];
  22. foreach ($xml as $key => $value) {
  23. if (isset($value->{$key})) {
  24. $i = 0;
  25. foreach ($value->{$key} as $v) {
  26. $array[$key][$i++] = (string)$v;
  27. }
  28. } else {
  29. // try to transform it into string value, trimming spaces between elements
  30. $array[$key] = trim((string)$value);
  31. if (empty($array[$key]) && !empty($value)) {
  32. $array[$key] = $this->xmlToAssoc($value);
  33. } else {
  34. // untrim strings values
  35. $array[$key] = (string)$value;
  36. }
  37. }
  38. }
  39. return $array;
  40. }
  41. }