PageRenderTime 55ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Json.php

https://bitbucket.org/baruffaldi/webapp-urltube
PHP | 242 lines | 71 code | 24 blank | 147 comment | 20 complexity | 462588d300973257777f25658f89e0ec MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, MIT
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Json
  17. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /**
  21. * Zend_Json_Exception.
  22. */
  23. require_once 'Zend/Json/Exception.php';
  24. /**
  25. * Class for encoding to and decoding from JSON.
  26. *
  27. * @category Zend
  28. * @package Zend_Json
  29. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  30. * @license http://framework.zend.com/license/new-bsd New BSD License
  31. */
  32. class Zend_Json
  33. {
  34. /**
  35. * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
  36. * so that it is a boolean true value, allowing it to be used with
  37. * ext/json's functions.
  38. */
  39. const TYPE_ARRAY = 1;
  40. const TYPE_OBJECT = 0;
  41. /**
  42. * To check the allowed nesting depth of the XML tree during xml2json conversion.
  43. *
  44. * @var int
  45. */
  46. public static $maxRecursionDepthAllowed=25;
  47. /**
  48. * @var bool
  49. */
  50. public static $useBuiltinEncoderDecoder = false;
  51. /**
  52. * Decodes the given $encodedValue string which is
  53. * encoded in the JSON format
  54. *
  55. * Uses ext/json's json_decode if available.
  56. *
  57. * @param string $encodedValue Encoded in JSON format
  58. * @param int $objectDecodeType Optional; flag indicating how to decode
  59. * objects. See {@link Zend_Json_Decoder::decode()} for details.
  60. * @return mixed
  61. */
  62. public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
  63. {
  64. if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
  65. return json_decode($encodedValue, $objectDecodeType);
  66. }
  67. require_once 'Zend/Json/Decoder.php';
  68. return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
  69. }
  70. /**
  71. * Encode the mixed $valueToEncode into the JSON format
  72. *
  73. * Encodes using ext/json's json_encode() if available.
  74. *
  75. * NOTE: Object should not contain cycles; the JSON format
  76. * does not allow object reference.
  77. *
  78. * NOTE: Only public variables will be encoded
  79. *
  80. * @param mixed $valueToEncode
  81. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  82. * @param array $options Additional options used during encoding
  83. * @return string JSON encoded object
  84. */
  85. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  86. {
  87. if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
  88. return json_encode($valueToEncode);
  89. }
  90. require_once 'Zend/Json/Encoder.php';
  91. return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);
  92. }
  93. /**
  94. * fromXml - Converts XML to JSON
  95. *
  96. * Converts a XML formatted string into a JSON formatted string.
  97. * The value returned will be a string in JSON format.
  98. *
  99. * The caller of this function needs to provide only the first parameter,
  100. * which is an XML formatted String. The second parameter is optional, which
  101. * lets the user to select if the XML attributes in the input XML string
  102. * should be included or ignored in xml2json conversion.
  103. *
  104. * This function converts the XML formatted string into a PHP array by
  105. * calling a recursive (protected static) function in this class. Then, it
  106. * converts that PHP array into JSON by calling the "encode" static funcion.
  107. *
  108. * Throws a Zend_Json_Exception if the input not a XML formatted string.
  109. *
  110. * @static
  111. * @access public
  112. * @param string $xmlStringContents XML String to be converted
  113. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  114. * the xml2json conversion process.
  115. * @return mixed - JSON formatted string on success
  116. * @throws Zend_Json_Exception
  117. */
  118. public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) {
  119. // Load the XML formatted string into a Simple XML Element object.
  120. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  121. // If it is not a valid XML content, throw an exception.
  122. if ($simpleXmlElementObject == null) {
  123. throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
  124. } // End of if ($simpleXmlElementObject == null)
  125. $resultArray = null;
  126. // Call the recursive function to convert the XML into a PHP array.
  127. $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  128. // Convert the PHP array to JSON using Zend_Json encode method.
  129. // It is just that simple.
  130. $jsonStringOutput = self::encode($resultArray);
  131. return($jsonStringOutput);
  132. } // End of function fromXml.
  133. /**
  134. * _processXml - Contains the logic for xml2json
  135. *
  136. * The logic in this function is a recursive one.
  137. *
  138. * The main caller of this function (i.e. fromXml) needs to provide
  139. * only the first two parameters i.e. the SimpleXMLElement object and
  140. * the flag for ignoring or not ignoring XML attributes. The third parameter
  141. * will be used internally within this function during the recursive calls.
  142. *
  143. * This function converts the SimpleXMLElement object into a PHP array by
  144. * calling a recursive (protected static) function in this class. Once all
  145. * the XML elements are stored in the PHP array, it is returned to the caller.
  146. *
  147. * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
  148. *
  149. * @static
  150. * @access protected
  151. * @param SimpleXMLElement $simpleXmlElementObject XML element to be converted
  152. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  153. * the xml2json conversion process.
  154. * @param int $recursionDepth Current recursion depth of this function
  155. * @return mixed - On success, a PHP associative array of traversed XML elements
  156. * @throws Zend_Json_Exception
  157. */
  158. protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) {
  159. // Keep an eye on how deeply we are involved in recursion.
  160. if ($recursionDepth > self::$maxRecursionDepthAllowed) {
  161. // XML tree is too deep. Exit now by throwing an exception.
  162. throw new Zend_Json_Exception(
  163. "Function _processXml exceeded the allowed recursion depth of " .
  164. self::$maxRecursionDepthAllowed);
  165. } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
  166. if ($recursionDepth == 0) {
  167. // Store the original SimpleXmlElementObject sent by the caller.
  168. // We will need it at the very end when we return from here for good.
  169. $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;
  170. } // End of if ($recursionDepth == 0)
  171. if ($simpleXmlElementObject instanceof SimpleXMLElement) {
  172. // Get a copy of the simpleXmlElementObject
  173. $copyOfSimpleXmlElementObject = $simpleXmlElementObject;
  174. // Get the object variables in the SimpleXmlElement object for us to iterate.
  175. $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);
  176. } // End of if (get_class($simpleXmlElementObject) == "SimpleXMLElement")
  177. // It needs to be an array of object variables.
  178. if (is_array($simpleXmlElementObject)) {
  179. // Initialize a result array.
  180. $resultArray = array();
  181. // Is the input array size 0? Then, we reached the rare CDATA text if any.
  182. if (count($simpleXmlElementObject) <= 0) {
  183. // Let us return the lonely CDATA. It could even be
  184. // an empty element or just filled with whitespaces.
  185. return (trim(strval($copyOfSimpleXmlElementObject)));
  186. } // End of if (count($simpleXmlElementObject) <= 0)
  187. // Let us walk through the child elements now.
  188. foreach($simpleXmlElementObject as $key=>$value) {
  189. // Check if we need to ignore the XML attributes.
  190. // If yes, you can skip processing the XML attributes.
  191. // Otherwise, add the XML attributes to the result array.
  192. if(($ignoreXmlAttributes == true) && (is_string($key)) && ($key == "@attributes")) {
  193. continue;
  194. } // End of if(($ignoreXmlAttributes == true) && ($key == "@attributes"))
  195. // Let us recursively process the current XML element we just visited.
  196. // Increase the recursion depth by one.
  197. $recursionDepth++;
  198. $resultArray[$key] = self::_processXml ($value, $ignoreXmlAttributes, $recursionDepth);
  199. // Decrease the recursion depth by one.
  200. $recursionDepth--;
  201. } // End of foreach($simpleXmlElementObject as $key=>$value) {
  202. if ($recursionDepth == 0) {
  203. // That is it. We are heading to the exit now.
  204. // Set the XML root element name as the root [top-level] key of
  205. // the associative array that we are going to return to the original
  206. // caller of this recursive function.
  207. $tempArray = $resultArray;
  208. $resultArray = array();
  209. $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;
  210. } // End of if ($recursionDepth == 0)
  211. return($resultArray);
  212. } else {
  213. // We are now looking at either the XML attribute text or
  214. // the text between the XML tags.
  215. return (trim(strval($simpleXmlElementObject)));
  216. } // End of if (is_array($simpleXmlElementObject))
  217. } // End of function _processXml.
  218. }