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.
17 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
18 * @license http://framework.zend.com/license/new-bsd New BSD License
26 require_once 'Zend/Json/Expr.php';
30 * Class for encoding to and decoding from JSON.
34 * @uses Zend_Json_Expr
35 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
36 * @license http://framework.zend.com/license/new-bsd New BSD License
41 * How objects should be encoded -- arrays or as StdClass. TYPE_ARRAY is 1
42 * so that it is a boolean true value, allowing it to be used with
43 * ext/json's functions.
46 const TYPE_OBJECT
= 0;
49 * To check the allowed nesting depth of the XML tree during xml2json conversion.
53 public static $maxRecursionDepthAllowed=25;
58 public static $useBuiltinEncoderDecoder = false;
61 * Decodes the given $encodedValue string which is
62 * encoded in the JSON format
64 * Uses ext/json's json_decode if available.
66 * @param string $encodedValue Encoded in JSON format
67 * @param int $objectDecodeType Optional; flag indicating how to decode
68 * objects. See {@link Zend_Json_Decoder::decode()} for details.
71 public static function decode($encodedValue, $objectDecodeType = Zend_Json
::TYPE_ARRAY
)
73 if (function_exists('json_decode') && self
::$useBuiltinEncoderDecoder !== true) {
74 return json_decode($encodedValue, $objectDecodeType);
77 require_once 'Zend/Json/Decoder.php';
78 return Zend_Json_Decoder
::decode($encodedValue, $objectDecodeType);
82 * Encode the mixed $valueToEncode into the JSON format
84 * Encodes using ext/json's json_encode() if available.
86 * NOTE: Object should not contain cycles; the JSON format
87 * does not allow object reference.
89 * NOTE: Only public variables will be encoded
91 * NOTE: Encoding native javascript expressions are possible using Zend_Json_Expr.
92 * You can enable this by setting $options['enableJsonExprFinder'] = true
96 * @param mixed $valueToEncode
97 * @param boolean $cycleCheck Optional; whether or not to check for object recursion; off by default
98 * @param array $options Additional options used during encoding
99 * @return string JSON encoded object
101 public static function encode($valueToEncode, $cycleCheck = false, $options = array())
103 if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
104 return $valueToEncode->toJson();
107 // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids
108 $javascriptExpressions = array();
109 if(isset($options['enableJsonExprFinder'])
110 && ($options['enableJsonExprFinder'] == true)
113 * @see Zend_Json_Encoder
115 require_once "Zend/Json/Encoder.php";
116 $valueToEncode = self
::_recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
120 if (function_exists('json_encode') && self
::$useBuiltinEncoderDecoder !== true) {
121 $encodedResult = json_encode($valueToEncode);
123 require_once 'Zend/Json/Encoder.php';
124 $encodedResult = Zend_Json_Encoder
::encode($valueToEncode, $cycleCheck, $options);
127 //only do post-proccessing to revert back the Zend_Json_Expr if any.
128 if (count($javascriptExpressions) > 0) {
129 $count = count($javascriptExpressions);
130 for($i = 0; $i < $count; $i++
) {
131 $magicKey = $javascriptExpressions[$i]['magicKey'];
132 $value = $javascriptExpressions[$i]['value'];
134 $encodedResult = str_replace(
135 //instead of replacing "key:magicKey", we replace directly magicKey by value because "key" never changes.
136 '"' . $magicKey . '"',
143 return $encodedResult;
147 * Check & Replace Zend_Json_Expr for tmp ids in the valueToEncode
149 * Check if the value is a Zend_Json_Expr, and if replace its value
150 * with a magic key and save the javascript expression in an array.
152 * NOTE this method is recursive.
154 * NOTE: This method is used internally by the encode method.
157 * @param mixed $valueToCheck a string - object property to be encoded
160 protected static function _recursiveJsonExprFinder(
161 &$value, array &$javascriptExpressions, $currentKey = null
163 if ($value instanceof Zend_Json_Expr
) {
164 // TODO: Optimize with ascii keys, if performance is bad
165 $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
166 $javascriptExpressions[] = array(
168 //if currentKey is integer, encodeUnicodeString call is not required.
169 "magicKey" => (is_int($currentKey)) ?
$magicKey : Zend_Json_Encoder
::encodeUnicodeString($magicKey),
170 "value" => $value->__toString(),
173 } elseif (is_array($value)) {
174 foreach ($value as $k => $v) {
175 $value[$k] = self
::_recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
177 } elseif (is_object($value)) {
178 foreach ($value as $k => $v) {
179 $value->$k = self
::_recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
186 * fromXml - Converts XML to JSON
188 * Converts a XML formatted string into a JSON formatted string.
189 * The value returned will be a string in JSON format.
191 * The caller of this function needs to provide only the first parameter,
192 * which is an XML formatted String. The second parameter is optional, which
193 * lets the user to select if the XML attributes in the input XML string
194 * should be included or ignored in xml2json conversion.
196 * This function converts the XML formatted string into a PHP array by
197 * calling a recursive (protected static) function in this class. Then, it
198 * converts that PHP array into JSON by calling the "encode" static funcion.
200 * Throws a Zend_Json_Exception if the input not a XML formatted string.
201 * NOTE: Encoding native javascript expressions via Zend_Json_Expr is not possible.
205 * @param string $xmlStringContents XML String to be converted
206 * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
207 * the xml2json conversion process.
208 * @return mixed - JSON formatted string on success
209 * @throws Zend_Json_Exception
211 public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) {
212 // Load the XML formatted string into a Simple XML Element object.
213 $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
215 // If it is not a valid XML content, throw an exception.
216 if ($simpleXmlElementObject == null) {
217 require_once 'Zend/Json/Exception.php';
218 throw new Zend_Json_Exception('Function fromXml was called with an invalid XML formatted string.');
219 } // End of if ($simpleXmlElementObject == null)
223 // Call the recursive function to convert the XML into a PHP array.
224 $resultArray = self
::_processXml($simpleXmlElementObject, $ignoreXmlAttributes);
226 // Convert the PHP array to JSON using Zend_Json encode method.
227 // It is just that simple.
228 $jsonStringOutput = self
::encode($resultArray);
229 return($jsonStringOutput);
230 } // End of function fromXml.
233 * _processXml - Contains the logic for xml2json
235 * The logic in this function is a recursive one.
237 * The main caller of this function (i.e. fromXml) needs to provide
238 * only the first two parameters i.e. the SimpleXMLElement object and
239 * the flag for ignoring or not ignoring XML attributes. The third parameter
240 * will be used internally within this function during the recursive calls.
242 * This function converts the SimpleXMLElement object into a PHP array by
243 * calling a recursive (protected static) function in this class. Once all
244 * the XML elements are stored in the PHP array, it is returned to the caller.
246 * Throws a Zend_Json_Exception if the XML tree is deeper than the allowed limit.
250 * @param SimpleXMLElement $simpleXmlElementObject XML element to be converted
251 * @param boolean $ignoreXmlAttributes Include or exclude XML attributes in
252 * the xml2json conversion process.
253 * @param int $recursionDepth Current recursion depth of this function
254 * @return mixed - On success, a PHP associative array of traversed XML elements
255 * @throws Zend_Json_Exception
257 protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) {
258 // Keep an eye on how deeply we are involved in recursion.
259 if ($recursionDepth > self
::$maxRecursionDepthAllowed) {
260 // XML tree is too deep. Exit now by throwing an exception.
261 require_once 'Zend/Json/Exception.php';
262 throw new Zend_Json_Exception(
263 "Function _processXml exceeded the allowed recursion depth of " .
264 self
::$maxRecursionDepthAllowed);
265 } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
267 if ($recursionDepth == 0) {
268 // Store the original SimpleXmlElementObject sent by the caller.
269 // We will need it at the very end when we return from here for good.
270 $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject;
271 } // End of if ($recursionDepth == 0)
273 if ($simpleXmlElementObject instanceof SimpleXMLElement
) {
274 // Get a copy of the simpleXmlElementObject
275 $copyOfSimpleXmlElementObject = $simpleXmlElementObject;
276 // Get the object variables in the SimpleXmlElement object for us to iterate.
277 $simpleXmlElementObject = get_object_vars($simpleXmlElementObject);
278 } // End of if (get_class($simpleXmlElementObject) == "SimpleXMLElement")
280 // It needs to be an array of object variables.
281 if (is_array($simpleXmlElementObject)) {
282 // Initialize a result array.
283 $resultArray = array();
284 // Is the input array size 0? Then, we reached the rare CDATA text if any.
285 if (count($simpleXmlElementObject) <= 0) {
286 // Let us return the lonely CDATA. It could even be
287 // an empty element or just filled with whitespaces.
288 return (trim(strval($copyOfSimpleXmlElementObject)));
289 } // End of if (count($simpleXmlElementObject) <= 0)
291 // Let us walk through the child elements now.
292 foreach($simpleXmlElementObject as $key=>$value) {
293 // Check if we need to ignore the XML attributes.
294 // If yes, you can skip processing the XML attributes.
295 // Otherwise, add the XML attributes to the result array.
296 if(($ignoreXmlAttributes == true) && (is_string($key)) && ($key == "@attributes")) {
298 } // End of if(($ignoreXmlAttributes == true) && ($key == "@attributes"))
300 // Let us recursively process the current XML element we just visited.
301 // Increase the recursion depth by one.
303 $resultArray[$key] = self
::_processXml ($value, $ignoreXmlAttributes, $recursionDepth);
305 // Decrease the recursion depth by one.
307 } // End of foreach($simpleXmlElementObject as $key=>$value) {
309 if ($recursionDepth == 0) {
310 // That is it. We are heading to the exit now.
311 // Set the XML root element name as the root [top-level] key of
312 // the associative array that we are going to return to the original
313 // caller of this recursive function.
314 $tempArray = $resultArray;
315 $resultArray = array();
316 $resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;
317 } // End of if ($recursionDepth == 0)
319 return($resultArray);
321 // We are now looking at either the XML attribute text or
322 // the text between the XML tags.
324 // In order to allow Zend_Json_Expr from xml, we check if the node
325 // matchs the pattern that try to detect if it is a new Zend_Json_Expr
326 // if it matches, we return a new Zend_Json_Expr instead of a text node
327 $pattern = '/^[\s]*new Zend_Json_Expr[\s]*\([\s]*[\"\']{1}(.*)[\"\']{1}[\s]*\)[\s]*$/';
328 $matchings = array();
329 $match = preg_match ($pattern, $simpleXmlElementObject, $matchings);
331 return new Zend_Json_Expr($matchings[1]);
333 return (trim(strval($simpleXmlElementObject)));
336 } // End of if (is_array($simpleXmlElementObject))
337 } // End of function _processXml.