Source for file StringJSON.php
Documentation is available at StringJSON.php
* Load FluentDOM from JSON encoded string
* @version $Id: StringJSON.php 431 2010-03-29 20:42:04Z subjective $
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @copyright Copyright (c) 2009 Bastian Feder, Thomas Weinert
require_once(dirname(__FILE__ ). '/../Loader.php');
* Load FluentDOM from JSON encoded string
* @example json/jsonToXml.php Usage Example: FluentDOMLoaderStringJSON
- 1 => 'Unknown error has occurred',
0 => 'No error has occurred',
1 => 'The maximum stack depth has been exceeded',
3 => 'Control character error, possibly incorrectly encoded',
* Add variable type attributes to the element nodes
* Load DOMDocument from local XML file
* @param string $source json encoded content
* @param string $contentType
* @return array(DOMDocument,DOMNode)|FALSE
public function load($source, $contentType) {
if (in_array($firstChar, array('{', '['))) {
$dom = new DOMDocument();
$documentElement = $dom->createElement('json');
$dom->appendChild($documentElement);
$this->_toDom($documentElement, $json);
return array($dom, array($documentElement));
$code = is_callable('json_last_error') ? json_last_error() : - 1;
throw new UnexpectedValueException($this->jsonErrors[$code]);
* Convert a JSON object structure to a DOMDocument
* @param DOMElement $parentNode
* @param integer $maxDepth simple recursion protection
private function _toDom($parentNode, $current, $maxDepth = 100) {
if (is_array($current) && $maxDepth > 0) {
foreach ($current as $index => $child) {
$childNode = $this->_addElement($parentNode, $parentNode->tagName. '-child');
$this->_toDom($childNode, $child, $maxDepth - 1);
} elseif (is_object($current) && $maxDepth > 0) {
$this->_toDom($childNode, $child, $maxDepth - 1);
$parentNode->appendChild(
$parentNode->ownerDocument->createTextNode($current ? '1' : '0')
} elseif (!empty($current)) {
$parentNode->appendChild(
$parentNode->ownerDocument->createTextNode((string) $current)
$parentNode->setAttribute('type', gettype($current));
* Add new element, sanitize tag name if nessesary
* @param DOMElement $parentNode
'\\x{C0}-\\x{D6}\\x{D8}-\\x{F6}\\x{F8}-\\x{2FF}\\x{370}-\\x{37D}'.
'\\x{37F}-\\x{1FFF}\\x{200C}-\\x{200D}\\x{2070}-\\x{218F}'.
'\\x{2C00}-\\x{2FEF}\\x{3001}-\\x{D7FF}\\x{F900}-\\x{FDCF}'.
'\\x{FDF0}-\\x{FFFD}\\x{10000}-\\x{EFFFF}';
'\\.\\d\\x{B7}\\x{300}-\\x{36F}\\x{203F}-\\x{2040}';
'((^[^'. $nameStartChar. '])|[^'. $nameChar. '])u', '-', $tagName
$childNode = $parentNode->ownerDocument->createElement($tagNameNormalized);
if ($tagNameNormalized != $tagName) {
$childNode->setAttribute('name', $tagName);
$parentNode->appendChild($childNode);
|