aaa - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of aaa.php

  1. <?php
  2. /**
  3.  * Array2XML: A class to convert array in PHP to XML
  4.  * It also takes into account attributes names unlike SimpleXML in PHP
  5.  * It returns the XML in form of DOMDocument class for further manipulation.
  6.  * It throws exception if the tag name or attribute name has illegal chars.
  7.  *
  8.  * Author : Lalit Patel
  9.  * Website: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
  10.  * License: Apache License 2.0
  11.  *          http://www.apache.org/licenses/LICENSE-2.0
  12.  * Version: 0.1 (10 July 2011)
  13.  * Version: 0.2 (16 August 2011)
  14.  *          - replaced htmlentities() with htmlspecialchars() (Thanks to Liel Dulev)
  15.  *          - fixed a edge case where root node has a false/null/0 value. (Thanks to Liel Dulev)
  16.  * Version: 0.3 (22 August 2011)
  17.  *          - fixed tag sanitize regex which didn't allow tagnames with single character.
  18.  * Version: 0.4 (18 September 2011)
  19.  *          - Added support for CDATA section using @cdata instead of @value.
  20.  * Version: 0.5 (07 December 2011)
  21.  *          - Changed logic to check numeric array indices not starting from 0.
  22.  * Version: 0.6 (04 March 2012)
  23.  *          - Code now doesn't @cdata to be placed in an empty array
  24.  * Version: 0.7 (24 March 2012)
  25.  *          - Reverted to version 0.5
  26.  * Version: 0.8 (02 May 2012)
  27.  *          - Removed htmlspecialchars() before adding to text node or attributes.
  28.  *
  29.  * Usage:
  30.  *       $xml = Array2XML::createXML('root_node_name', $php_array);
  31.  *       echo $xml->saveXML();
  32.  */
  33. class Array2XML {
  34.     private static $xml = null;
  35.   private static $encoding = 'UTF-8';
  36.     /**
  37.      * Initialize the root XML node [optional]
  38.      * @param $version
  39.      * @param $encoding
  40.      * @param $format_output
  41.      */
  42.     public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
  43.         self::$xml = new DomDocument($version, $encoding);
  44.         self::$xml->formatOutput = $format_output;
  45.                 self::$encoding = $encoding;
  46.     }
  47.     /**
  48.      * Convert an Array to XML
  49.      * @param string $node_name - name of the root node to be converted
  50.      * @param array $arr - aray to be converterd
  51.      * @return DomDocument
  52.      */
  53.     public static function &createXML($node_name, $arr=array()) {
  54.         $xml = self::getXMLRoot();
  55.         $xml->appendChild(self::convert($node_name, $arr));
  56.         self::$xml = null;    // clear the xml node in the class for 2nd time use.
  57.         return $xml;
  58.     }
  59.     /**
  60.      * Convert an Array to XML
  61.      * @param string $node_name - name of the root node to be converted
  62.      * @param array $arr - aray to be converterd
  63.      * @return DOMNode
  64.      */
  65.     private static function &convert($node_name, $arr=array()) {
  66.         //print_arr($node_name);
  67.         $xml = self::getXMLRoot();
  68.         $node = $xml->createElement($node_name);
  69.         if(is_array($arr)){
  70.             // get the attributes first.;
  71.             if(isset($arr['@attributes'])) {
  72.                 foreach($arr['@attributes'] as $key => $value) {
  73.                     if(!self::isValidTagName($key)) {
  74.                         throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
  75.                     }
  76.                     $node->setAttribute($key, self::bool2str($value));
  77.                 }
  78.                 unset($arr['@attributes']); //remove the key from the array once done.
  79.             }
  80.             // check if it has a value stored in @value, if yes store the value and return
  81.             // else check if its directly stored as string
  82.             if(isset($arr['@value'])) {
  83.                 $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
  84.                 unset($arr['@value']);    //remove the key from the array once done.
  85.                 //return from recursion, as a note with value cannot have child nodes.
  86.                 return $node;
  87.             } else if(isset($arr['@cdata'])) {
  88.                 $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
  89.                 unset($arr['@cdata']);    //remove the key from the array once done.
  90.                 //return from recursion, as a note with cdata cannot have child nodes.
  91.                 return $node;
  92.             }
  93.         }
  94.         //create subnodes using recursion
  95.         if(is_array($arr)){
  96.             // recurse to get the node for that key
  97.             foreach($arr as $key=>$value){
  98.                 if(!self::isValidTagName($key)) {
  99.                     throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
  100.                 }
  101.                 if(is_array($value) && is_numeric(key($value))) {
  102.                     // MORE THAN ONE NODE OF ITS KIND;
  103.                     // if the new array is numeric index, means it is array of nodes of the same kind
  104.                     // it should follow the parent key name
  105.                     foreach($value as $k=>$v){
  106.                         $node->appendChild(self::convert($key, $v));
  107.                     }
  108.                 } else {
  109.                     // ONLY ONE NODE OF ITS KIND
  110.                     $node->appendChild(self::convert($key, $value));
  111.                 }
  112.                 unset($arr[$key]); //remove the key from the array once done.
  113.             }
  114.         }
  115.         // after we are done with all the keys in the array (if it is one)
  116.         // we check if it has any text value, if yes, append it.
  117.         if(!is_array($arr)) {
  118.             $node->appendChild($xml->createTextNode(self::bool2str($arr)));
  119.         }
  120.         return $node;
  121.     }
  122.     /*
  123.      * Get the root XML node, if there isn't one, create it.
  124.      */
  125.     private static function getXMLRoot(){
  126.         if(empty(self::$xml)) {
  127.             self::init();
  128.         }
  129.         return self::$xml;
  130.     }
  131.     /*
  132.      * Get string representation of boolean value
  133.      */
  134.     private static function bool2str($v){
  135.         //convert boolean to text value.
  136.         $v = $v === true ? 'true' : $v;
  137.         $v = $v === false ? 'false' : $v;
  138.         return $v;
  139.     }
  140.     /*
  141.      * Check if the tag name or attribute name contains illegal characters
  142.      * Ref: http://www.w3.org/TR/xml/#sec-common-syn
  143.      */
  144.     private static function isValidTagName($tag){
  145.         $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
  146.         return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
  147.     }
  148. }
  149.  
  150. $json = '{"website":{"domain":"wtools.io","title":"Online Web Tools"}}';
  151. $php_array = json_decode($json, true);
  152. $xml = Array2XML::createXML('root-element-here', $php_array);
  153. echo $xml->saveXML();
  154.  
File Description
  • aaa
  • PHP Code
  • 29 Aug-2019
  • 6.39 Kb
You can Share it: