コード例 #1
0
ファイル: class.json.php プロジェクト: jurajkapsz/symphony-2
 /**
  * Given a JSON formatted string, this function will convert it to an
  * equivalent XML version (either standalone or as a fragment). The JSON
  * will be added under a root node of `<data>`.
  *
  * @throws JSONException
  * @param string $json
  *  The JSON formatted class
  * @param boolean $standalone
  *  If passed true (which is the default), this parameter will cause
  *  the function to return the XML with an XML declaration, otherwise
  *  the XML will be returned as a fragment.
  * @return string
  *  Returns a XML string
  */
 public static function convertToXML($json, $standalone = true)
 {
     self::$dom = new DomDocument('1.0', 'utf-8');
     self::$dom->formatOutput = true;
     // remove callback functions from JSONP
     if (preg_match('/(\\{|\\[).*(\\}|\\])/s', $json, $matches)) {
         $json = $matches[0];
     } else {
         throw new JSONException(__("JSON not formatted correctly"));
     }
     $data = json_decode($json);
     if (function_exists('json_last_error')) {
         if (json_last_error() !== JSON_ERROR_NONE) {
             throw new JSONException(__("JSON not formatted correctly"), json_last_error());
         }
     } elseif (!$data) {
         throw new JSONException(__("JSON not formatted correctly"));
     }
     $data_element = self::_process($data, self::$dom->createElement('data'));
     self::$dom->appendChild($data_element);
     if ($standalone) {
         return self::$dom->saveXML();
     } else {
         return self::$dom->saveXML(self::$dom->documentElement);
     }
 }