人人商城

xml2json.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. class xml2json
  3. {
  4. static public function transformXmlStringToJson($xmlStringContents)
  5. {
  6. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  7. if ($simpleXmlElementObject == NULL) {
  8. return EMPTY_STR;
  9. }
  10. $simpleXmlRootElementName = $simpleXmlElementObject->getName();
  11. if (DEBUG) {
  12. }
  13. $jsonOutput = EMPTY_STR;
  14. $array1 = xml2json::convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject);
  15. if ($array1 != NULL && 0 < sizeof($array1)) {
  16. $json = new Services_JSON();
  17. $jsonOutput = $json->encode($array1);
  18. if (DEBUG) {
  19. }
  20. }
  21. return $jsonOutput;
  22. }
  23. static public function convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject, &$recursionDepth = 0)
  24. {
  25. if (MAX_RECURSION_DEPTH_ALLOWED < $recursionDepth) {
  26. return NULL;
  27. }
  28. if ($recursionDepth == 0) {
  29. if (get_class($simpleXmlElementObject) != SIMPLE_XML_ELEMENT_PHP_CLASS) {
  30. return NULL;
  31. }
  32. $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;
  33. }
  34. if (@get_class($simpleXmlElementObject) == SIMPLE_XML_ELEMENT_PHP_CLASS) {
  35. $copyOfsimpleXmlElementObject = $simpleXmlElementObject;
  36. $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);
  37. }
  38. if (is_array($simpleXmlElementObject)) {
  39. $resultArray = array();
  40. if (count($simpleXmlElementObject) <= 0) {
  41. return trim(strval($copyOfsimpleXmlElementObject));
  42. }
  43. foreach ($simpleXmlElementObject as $key => $value) {
  44. ++$recursionDepth;
  45. $resultArray[$key] = xml2json::convertSimpleXmlElementObjectIntoArray($value, $recursionDepth);
  46. --$recursionDepth;
  47. }
  48. if ($recursionDepth == 0) {
  49. $tempArray = $resultArray;
  50. $resultArray = array();
  51. $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;
  52. }
  53. return $resultArray;
  54. }
  55. return trim(strval($simpleXmlElementObject));
  56. }
  57. }
  58. require_once 'JSON.php';
  59. define('DEBUG', false);
  60. define('MAX_RECURSION_DEPTH_ALLOWED', 25);
  61. define('EMPTY_STR', '');
  62. define('SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES', '@attributes');
  63. define('SIMPLE_XML_ELEMENT_PHP_CLASS', 'SimpleXMLElement');
  64. ?>