diff --git a/.gitignore b/.gitignore index de4a392..1ee4bf6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ +.idea /vendor /composer.lock diff --git a/LSS/Array2XML.php b/LSS/Array2XML.php index 4b91f47..99e0659 100644 --- a/LSS/Array2XML.php +++ b/LSS/Array2XML.php @@ -2,23 +2,24 @@ /** * OpenLSS - Lighter Smarter Simpler * - * This file is part of OpenLSS. + * This file is part of OpenLSS. * - * OpenLSS is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. + * OpenLSS is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of + * the License, or (at your option) any later version. * - * OpenLSS is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. + * OpenLSS is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. * - * You should have received a copy of the - * GNU Lesser General Public License along with OpenLSS. - * If not, see . -*/ + * You should have received a copy of the + * GNU Lesser General Public License along with OpenLSS. + * If not, see . + */ namespace LSS; + use \DomDocument; use \Exception; @@ -48,16 +49,20 @@ * - Reverted to version 0.5 * Version: 0.8 (02 May 2012) * - Removed htmlspecialchars() before adding to text node or attributes. + * Version: 0.11 (28 October 2015) + * - Fixed typos; Added support for plain insertion of XML trough @xml. * * Usage: * $xml = Array2XML::createXML('root_node_name', $php_array); * echo $xml->saveXML(); */ - class Array2XML { + /** + * @var DOMDocument + */ private static $xml = null; - private static $encoding = 'UTF-8'; + private static $encoding = 'UTF-8'; /** * Initialize the root XML node [optional] @@ -68,7 +73,7 @@ class Array2XML { public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) { self::$xml = new DomDocument($version, $encoding); self::$xml->formatOutput = $format_output; - self::$encoding = $encoding; + self::$encoding = $encoding; } /** @@ -77,7 +82,7 @@ public static function init($version = '1.0', $encoding = 'UTF-8', $format_outpu * @param array $arr - aray to be converterd * @return DomDocument */ - public static function &createXML($node_name, $arr=array()) { + public static function &createXML($node_name, $arr = array()) { $xml = self::getXMLRoot(); $xml->appendChild(self::convert($node_name, $arr)); @@ -86,23 +91,29 @@ public static function &createXML($node_name, $arr=array()) { } /** - * Convert an Array to XML - * @param string $node_name - name of the root node to be converted - * @param array $arr - aray to be converterd - * @return DOMNode + * Convert an Array to XML. + * + * @param string $node_name + * Name of the root node to be converted. + * @param array $arr + * Array to be converted. + * + * @throws \Exception + * + * @return \DOMNode */ - private static function &convert($node_name, $arr=array()) { + private static function &convert($node_name, $arr = array()) { //print_arr($node_name); $xml = self::getXMLRoot(); $node = $xml->createElement($node_name); - if(is_array($arr)){ + if (is_array($arr)) { // get the attributes first.; - if(isset($arr['@attributes'])) { - foreach($arr['@attributes'] as $key => $value) { - if(!self::isValidTagName($key)) { - throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name); + if (isset($arr['@attributes'])) { + foreach ($arr['@attributes'] as $key => $value) { + if (!self::isValidTagName($key)) { + throw new Exception('[Array2XML] Illegal character in attribute name. attribute: ' . $key . ' in node: ' . $node_name); } $node->setAttribute($key, self::bool2str($value)); } @@ -111,31 +122,42 @@ private static function &convert($node_name, $arr=array()) { // check if it has a value stored in @value, if yes store the value and return // else check if its directly stored as string - if(isset($arr['@value'])) { + if (isset($arr['@value'])) { $node->appendChild($xml->createTextNode(self::bool2str($arr['@value']))); unset($arr['@value']); //remove the key from the array once done. //return from recursion, as a note with value cannot have child nodes. return $node; - } else if(isset($arr['@cdata'])) { + } else if (isset($arr['@cdata'])) { $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata']))); unset($arr['@cdata']); //remove the key from the array once done. //return from recursion, as a note with cdata cannot have child nodes. return $node; } + else if (isset($arr['@comment']) && is_string($arr['@comment'])) { + $node->appendChild($xml->createComment(self::bool2str($arr['@comment']))); + unset($arr['@comment']); + } + else if (isset($arr['@xml'])) { + $fragment = $xml->createDocumentFragment(); + $fragment->appendXML($arr['@xml']); + $node->appendChild($fragment); + unset($arr['@xml']); + return $node; + } } //create subnodes using recursion - if(is_array($arr)){ + if (is_array($arr)) { // recurse to get the node for that key - foreach($arr as $key=>$value){ - if(!self::isValidTagName($key)) { - throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name); + foreach ($arr as $key => $value) { + if (!self::isValidTagName($key)) { + throw new Exception('[Array2XML] Illegal character in tag name. tag: ' . $key . ' in node: ' . $node_name); } - if(is_array($value) && is_numeric(key($value))) { + if (is_array($value) && is_numeric(key($value))) { // MORE THAN ONE NODE OF ITS KIND; // if the new array is numeric index, means it is array of nodes of the same kind // it should follow the parent key name - foreach($value as $k=>$v){ + foreach ($value as $k => $v) { $node->appendChild(self::convert($key, $v)); } } else { @@ -148,7 +170,7 @@ private static function &convert($node_name, $arr=array()) { // after we are done with all the keys in the array (if it is one) // we check if it has any text value, if yes, append it. - if(!is_array($arr)) { + if (!is_array($arr)) { $node->appendChild($xml->createTextNode(self::bool2str($arr))); } @@ -158,8 +180,8 @@ private static function &convert($node_name, $arr=array()) { /* * Get the root XML node, if there isn't one, create it. */ - private static function getXMLRoot(){ - if(empty(self::$xml)) { + private static function getXMLRoot() { + if (empty(self::$xml)) { self::init(); } return self::$xml; @@ -168,7 +190,7 @@ private static function getXMLRoot(){ /* * Get string representation of boolean value */ - private static function bool2str($v){ + private static function bool2str($v) { //convert boolean to text value. $v = $v === true ? 'true' : $v; $v = $v === false ? 'false' : $v; @@ -179,7 +201,7 @@ private static function bool2str($v){ * Check if the tag name or attribute name contains illegal characters * Ref: http://www.w3.org/TR/xml/#sec-common-syn */ - private static function isValidTagName($tag){ + private static function isValidTagName($tag) { $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i'; return preg_match($pattern, $tag, $matches) && $matches[0] == $tag; } diff --git a/LSS/XML2Array.php b/LSS/XML2Array.php index 18d4679..ad5dafa 100644 --- a/LSS/XML2Array.php +++ b/LSS/XML2Array.php @@ -43,8 +43,9 @@ class XML2Array { - private static $xml = null; - private static $encoding = 'UTF-8'; + protected static $xml = null; + protected static $encoding = 'UTF-8'; + protected static $prefix_attributes = '@'; /** * Initialize the root XML node [optional] @@ -61,13 +62,15 @@ public static function init($version = '1.0', $encoding = 'UTF-8', $format_outpu /** * Convert an XML to Array * @param string $node_name - name of the root node to be converted + * @param int - Bitwise OR of the libxml option constants see @link http://php.net/manual/libxml.constants.php * @param array $arr - aray to be converterd - * @return DOMDocument + * @param mixed $callback - callback function + * @return array */ - public static function &createArray($input_xml) { + public static function &createArray($input_xml, $options = 0, $callback = null) { $xml = self::getXMLRoot(); if(is_string($input_xml)) { - $parsed = $xml->loadXML($input_xml); + $parsed = $xml->loadXML($input_xml, $options); if(!$parsed) { throw new Exception('[XML2Array] Error parsing the XML string.'); } @@ -77,7 +80,7 @@ public static function &createArray($input_xml) { } $xml = self::$xml = $input_xml; } - $array[$xml->documentElement->tagName] = self::convert($xml->documentElement); + $array[$xml->documentElement->tagName] = self::convert($xml->documentElement, $callback); self::$xml = null; // clear the xml node in the class for 2nd time use. return $array; } @@ -85,14 +88,15 @@ public static function &createArray($input_xml) { /** * Convert an Array to XML * @param mixed $node - XML as a string or as an object of DOMDocument + * @param mixed $callback - callback function * @return mixed */ - private static function &convert($node) { + protected static function &convert($node, $callback = null) { $output = array(); switch ($node->nodeType) { case XML_CDATA_SECTION_NODE: - $output['@cdata'] = trim($node->textContent); + $output[static::$prefix_attributes.'cdata'] = trim($node->textContent); break; case XML_TEXT_NODE: @@ -100,14 +104,20 @@ private static function &convert($node) { break; case XML_ELEMENT_NODE: - // for each child node, call the covert function recursively for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) { + if ($callback!==null) { + $callback($m=$node->childNodes->length, $i); + } $child = $node->childNodes->item($i); $v = self::convert($child); if(isset($child->tagName)) { $t = $child->tagName; + // avoid fatal error if the content looks like 'You are being redirected.' + if(isset($output) && !is_array($output)) { + continue; + } // assume more nodes of same kind are coming if(!isset($output[$t])) { $output[$t] = array(); @@ -142,9 +152,9 @@ private static function &convert($node) { } // if its an leaf node, store the value in @value instead of directly storing it. if(!is_array($output)) { - $output = array('@value' => $output); + $output = array(static::$prefix_attributes.'value' => $output); } - $output['@attributes'] = $a; + $output[static::$prefix_attributes.'attributes'] = $a; } break; } @@ -154,7 +164,7 @@ private static function &convert($node) { /* * Get the root XML node, if there isn't one, create it. */ - private static function getXMLRoot(){ + protected static function getXMLRoot(){ if(empty(self::$xml)) { self::init(); } diff --git a/README.md b/README.md index 7abe66d..d3207ce 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,58 @@ $array = XML2Array::createArray($xml); print_r($array); ``` +Array2XML +---- + +@xml example: +```php +// Build the array that should be transformed into a XML object. +$array = [ + 'title' => 'A title', + 'body' => [ + '@xml' => '

The content for the news item

', + ], +]; + +// Use the Array2XML object to transform it. +$xml = Array2XML::createXML('news', $array); +echo $xml->saveXML(); +``` +This will result in the following. +```xml + + + A title + + + +

The content for the news item

+ + + +
+``` + Reference ---- More complete references can be found here http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array/ http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes/ +## Changelog + +### 1.0.0 +* Add ability for callbacks during processing to check status. + +### 0.5.1 +* Fix fata error when the array passed is empty fixed by pull request #6 + +### 0.5.0 +* add second parameter to XML2Array::createArray for DOMDocument::load, e.g: LIBXML_NOCDATA +* change method visibility from private to protected for overloading +* Merge pull request #5 to add child xml +* Merge pull request #4 to change method visibility and add second parameter for load. + + +### 0.1.0 +* Initial Release diff --git a/composer.json b/composer.json index 0a514c9..7471231 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "openlss/lib-array2xml" - ,"homepage": "http://openlss.org" + ,"homepage": "https://www.nullivex.com" ,"description": "Array2XML conversion library credit to lalit.org" ,"license": "Apache-2.0" ,"type": "library" @@ -13,13 +13,13 @@ ,"authors": [ { "name": "Bryan Tong" - ,"email": "contact@nullivex.com" - ,"homepage": "http://bryantong.com" + ,"email": "bryan@nullivex.com" + ,"homepage": "https://www.nullivex.com" } ,{ "name": "Tony Butler" ,"email": "spudz76@gmail.com" - ,"homepage": "http://openlss.org" + ,"homepage": "https://www.nullivex.com" } ] ,"require": {