Json.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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-2011 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * Zend_Json_Expr.
  23. *
  24. * @see Zend_Json_Expr
  25. */
  26. require_once 'Zend/Json/Expr.php';
  27. /**
  28. * Class for encoding to and decoding from JSON.
  29. *
  30. * @category Zend
  31. * @package Zend_Json
  32. * @uses Zend_Json_Expr
  33. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  34. * @license http://framework.zend.com/license/new-bsd New BSD License
  35. */
  36. class Zend_Json
  37. {
  38. /**
  39. * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
  40. * so that it is a boolean true value, allowing it to be used with
  41. * ext/json's functions.
  42. */
  43. const TYPE_ARRAY = 1;
  44. const TYPE_OBJECT = 0;
  45. /**
  46. * To check the allowed nesting depth of the XML tree during xml2json conversion.
  47. *
  48. * @var int
  49. */
  50. public static $maxRecursionDepthAllowed=25;
  51. /**
  52. * @var bool
  53. */
  54. public static $useBuiltinEncoderDecoder = false;
  55. /**
  56. * Decodes the given $encodedValue string which is
  57. * encoded in the JSON format
  58. *
  59. * Uses ext/json's json_decode if available.
  60. *
  61. * @param string $encodedValue Encoded in JSON format
  62. * @param int $objectDecodeType Optional; flag indicating how to decode
  63. * objects. See {@link Zend_Json_Decoder::decode()} for details.
  64. * @return mixed
  65. */
  66. public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
  67. {
  68. $encodedValue = (string) $encodedValue;
  69. if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
  70. $decode = json_decode($encodedValue, $objectDecodeType);
  71. // php < 5.3
  72. if (!function_exists('json_last_error')) {
  73. if ($decode === $encodedValue) {
  74. require_once 'Zend/Json/Exception.php';
  75. throw new Zend_Json_Exception('Decoding failed');
  76. }
  77. // php >= 5.3
  78. } elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
  79. require_once 'Zend/Json/Exception.php';
  80. switch ($jsonLastErr) {
  81. case JSON_ERROR_DEPTH:
  82. throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded');
  83. case JSON_ERROR_CTRL_CHAR:
  84. throw new Zend_Json_Exception('Decoding failed: Unexpected control character found');
  85. case JSON_ERROR_SYNTAX:
  86. throw new Zend_Json_Exception('Decoding failed: Syntax error');
  87. default:
  88. throw new Zend_Json_Exception('Decoding failed');
  89. }
  90. }
  91. return $decode;
  92. }
  93. require_once 'Zend/Json/Decoder.php';
  94. return Zend_Json_Decoder::decode($encodedValue, $objectDecodeType);
  95. }
  96. /**
  97. * Encode the mixed $valueToEncode into the JSON format
  98. *
  99. * Encodes using ext/json's json_encode() if available.
  100. *
  101. * NOTE: Object should not contain cycles; the JSON format
  102. * does not allow object reference.
  103. *
  104. * NOTE: Only public variables will be encoded
  105. *
  106. * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
  107. * You can enable this by setting $options['enableJsonExprFinder'] = true
  108. *
  109. * @see Zend_Json_Expr
  110. *
  111. * @param mixed $valueToEncode
  112. * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
  113. * @param array $options Additional options used during encoding
  114. * @return string JSON encoded object
  115. */
  116. public static function encode($valueToEncode, $cycleCheck = false, $options = array())
  117. {
  118. if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
  119. return $valueToEncode->toJson();
  120. }
  121. // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
  122. $javascriptExpressions = array();
  123. if(isset($options['enableJsonExprFinder'])
  124. && ($options['enableJsonExprFinder'] == true)
  125. ) {
  126. /**
  127. * @see Zend_Json_Encoder
  128. */
  129. require_once "Zend/Json/Encoder.php";
  130. $valueToEncode = self::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
  131. }
  132. // Encoding
  133. if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
  134. $encodedResult = json_encode($valueToEncode);
  135. } else {
  136. require_once 'Zend/Json/Encoder.php';
  137. $encodedResult = Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);
  138. }
  139. //only do post-proccessing to revert back the Zend_Json_Expr if any.
  140. if (count($javascriptExpressions) > 0) {
  141. $count = count($javascriptExpressions);
  142. for($i = 0; $i < $count; $i++) {
  143. $magicKey = $javascriptExpressions[$i]['magicKey'];
  144. $value = $javascriptExpressions[$i]['value'];
  145. $encodedResult = str_replace(
  146. //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
  147. '"' . $magicKey . '"',
  148. $value,
  149. $encodedResult
  150. );
  151. }
  152. }
  153. return $encodedResult;
  154. }
  155. /**
  156. * Check & Replace Zend_Json_Expr for tmp ids in the valueToEncode
  157. *
  158. * Check if the value is a Zend_Json_Expr, and if replace its value
  159. * with a magic key and save the javascript expression in an array.
  160. *
  161. * NOTE this method is recursive.
  162. *
  163. * NOTE: This method is used internally by the encode method.
  164. *
  165. * @see encode
  166. * @param mixed $valueToCheck a string - object property to be encoded
  167. * @return void
  168. */
  169. protected static function _recursiveJsonExprFinder(
  170. &$value, array &$javascriptExpressions, $currentKey = null
  171. ) {
  172. if ($value instanceof Zend_Json_Expr) {
  173. // TODO: Optimize with ascii keys, if performance is bad
  174. $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
  175. $javascriptExpressions[] = array(
  176. //if currentKey is integer, encodeUnicodeString call is not required.
  177. "magicKey" => (is_int($currentKey)) ? $magicKey : Zend_Json_Encoder::encodeUnicodeString($magicKey),
  178. "value" => $value->__toString(),
  179. );
  180. $value = $magicKey;
  181. } elseif (is_array($value)) {
  182. foreach ($value as $k => $v) {
  183. $value[$k] = self::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
  184. }
  185. } elseif (is_object($value)) {
  186. foreach ($value as $k => $v) {
  187. $value->$k = self::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
  188. }
  189. }
  190. return $value;
  191. }
  192. /**
  193. * Return the value of an XML attribute text or the text between
  194. * the XML tags
  195. *
  196. * In order to allow Zend_Json_Expr from xml, we check if the node
  197. * matchs the pattern that try to detect if it is a new Zend_Json_Expr
  198. * if it matches, we return a new Zend_Json_Expr instead of a text node
  199. *
  200. * @param SimpleXMLElement $simpleXmlElementObject
  201. * @return Zend_Json_Expr|string
  202. */
  203. protected static function _getXmlValue($simpleXmlElementObject) {
  204. $pattern = '/^[\s]*new Zend_Json_Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
  205. $matchings = array();
  206. $match = preg_match ($pattern, $simpleXmlElementObject, $matchings);
  207. if ($match) {
  208. return new Zend_Json_Expr($matchings[1]);
  209. } else {
  210. return (trim(strval($simpleXmlElementObject)));
  211. }
  212. }
  213. /**
  214. * _processXml - Contains the logic for xml2json
  215. *
  216. * The logic in this function is a recursive one.
  217. *
  218. * The main caller of this function (i.e. fromXml) needs to provide
  219. * only the first two parameters i.e. the SimpleXMLElement object and
  220. * the flag for ignoring or not ignoring XML attributes. The third parameter
  221. * will be used internally within this function during the recursive calls.
  222. *
  223. * This function converts the SimpleXMLElement object into a PHP array by
  224. * calling a recursive (protected static) function in this class. Once all
  225. * the XML elements are stored in the PHP array, it is returned to the caller.
  226. *
  227. * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
  228. *
  229. * @param SimpleXMLElement $simpleXmlElementObject
  230. * @param boolean $ignoreXmlAttributes
  231. * @param integer $recursionDepth
  232. * @return array
  233. */
  234. protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) {
  235. // Keep an eye on how deeply we are involved in recursion.
  236. if ($recursionDepth > self::$maxRecursionDepthAllowed) {
  237. // XML tree is too deep. Exit now by throwing an exception.
  238. require_once 'Zend/Json/Exception.php';
  239. throw new Zend_Json_Exception(
  240. "Function _processXml exceeded the allowed recursion depth of " .
  241. self::$maxRecursionDepthAllowed);
  242. } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
  243. $childrens= $simpleXmlElementObject->children();
  244. $name= $simpleXmlElementObject->getName();
  245. $value= self::_getXmlValue($simpleXmlElementObject);
  246. $attributes= (array) $simpleXmlElementObject->attributes();
  247. if (count($childrens)==0) {
  248. if (!empty($attributes) && !$ignoreXmlAttributes) {
  249. foreach ($attributes['@attributes'] as $k => $v) {
  250. $attributes['@attributes'][$k]= self::_getXmlValue($v);
  251. }
  252. if (!empty($value)) {
  253. $attributes['@text']= $value;
  254. }
  255. return array($name => $attributes);
  256. } else {
  257. return array($name => $value);
  258. }
  259. } else {
  260. $childArray= array();
  261. foreach ($childrens as $child) {
  262. $childname= $child->getName();
  263. $element= self::_processXml($child,$ignoreXmlAttributes,$recursionDepth+1);
  264. if (array_key_exists($childname, $childArray)) {
  265. if (empty($subChild[$childname])) {
  266. $childArray[$childname]=array($childArray[$childname]);
  267. $subChild[$childname]=true;
  268. }
  269. $childArray[$childname][]= $element[$childname];
  270. } else {
  271. $childArray[$childname]= $element[$childname];
  272. }
  273. }
  274. if (!empty($attributes) && !$ignoreXmlAttributes) {
  275. foreach ($attributes['@attributes'] as $k => $v) {
  276. $attributes['@attributes'][$k]= self::_getXmlValue($v);
  277. }
  278. $childArray['@attributes']= $attributes['@attributes'];
  279. }
  280. if (!empty($value)) {
  281. $childArray['@text']= $value;
  282. }
  283. return array($name => $childArray);
  284. }
  285. }
  286. /**
  287. * fromXml - Converts XML to JSON
  288. *
  289. * Converts a XML formatted string into a JSON formatted string.
  290. * The value returned will be a string in JSON format.
  291. *
  292. * The caller of this function needs to provide only the first parameter,
  293. * which is an XML formatted String. The second parameter is optional, which
  294. * lets the user to select if the XML attributes in the input XML string
  295. * should be included or ignored in xml2json conversion.
  296. *
  297. * This function converts the XML formatted string into a PHP array by
  298. * calling a recursive (protected static) function in this class. Then, it
  299. * converts that PHP array into JSON by calling the "encode" static funcion.
  300. *
  301. * Throws a Zend_Json_Exception if the input not a XML formatted string.
  302. * NOTE: Encoding native javascript expressions via Zend_Json_Expr is not possible.
  303. *
  304. * @static
  305. * @access public
  306. * @param string $xmlStringContents XML String to be converted
  307. * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
  308. * the xml2json conversion process.
  309. * @return mixed - JSON formatted string on success
  310. * @throws Zend_Json_Exception
  311. */
  312. public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) {
  313. // Load the XML formatted string into a Simple XML Element object.
  314. $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
  315. // If it is not a valid XML content, throw an exception.
  316. if ($simpleXmlElementObject == null) {
  317. require_once 'Zend/Json/Exception.php';
  318. throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
  319. } // End of if ($simpleXmlElementObject == null)
  320. $resultArray = null;
  321. // Call the recursive function to convert the XML into a PHP array.
  322. $resultArray = self::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
  323. // Convert the PHP array to JSON using Zend_Json encode method.
  324. // It is just that simple.
  325. $jsonStringOutput = self::encode($resultArray);
  326. return($jsonStringOutput);
  327. } // End of function fromXml.
  328. /**
  329. * Pretty-print JSON string
  330. *
  331. * Use 'indent' option to select indentation string - by default it's a tab
  332. *
  333. * @param string $json Original JSON string
  334. * @param array $options Encoding options
  335. * @return string
  336. */
  337. public static function prettyPrint($json, $options = array())
  338. {
  339. $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
  340. $result = "";
  341. $indent = 0;
  342. $ind = "\t";
  343. if(isset($options['indent'])) {
  344. $ind = $options['indent'];
  345. }
  346. foreach($tokens as $token) {
  347. if($token == "") continue;
  348. $prefix = str_repeat($ind, $indent);
  349. if($token == "{" || $token == "[") {
  350. $indent++;
  351. if($result != "" && $result[strlen($result)-1] == "\n") {
  352. $result .= $prefix;
  353. }
  354. $result .= "$token\n";
  355. } else if($token == "}" || $token == "]") {
  356. $indent--;
  357. $prefix = str_repeat($ind, $indent);
  358. $result .= "\n$prefix$token";
  359. } else if($token == ",") {
  360. $result .= "$token\n";
  361. } else {
  362. $result .= $prefix.$token;
  363. }
  364. }
  365. return $result;
  366. }
  367. }