Skip to content

Commit

Permalink
Merge pull request #13 from averichev/patch-2
Browse files Browse the repository at this point in the history
Added callback function
  • Loading branch information
nullivex committed Mar 29, 2019
2 parents f3a5bca + 9d2ab61 commit f3813a3
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions LSS/XML2Array.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,13 @@ public static function init($version = '1.0', $encoding = 'UTF-8', $format_outpu
* @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
* @param mixed $callback - callback function
* @return array
*/
public static function &createArray($input_xml, $options = 0) {
public static function &createArray($input_xml, $options = 0, $callback = null) {
$xml = self::getXMLRoot();
if(is_string($input_xml)) {
$parsed = @$xml->loadXML($input_xml, $options);
$parsed = $xml->loadXML($input_xml, $options);
if(!$parsed) {
throw new Exception('[XML2Array] Error parsing the XML string.');
}
Expand All @@ -79,17 +80,18 @@ public static function &createArray($input_xml, $options = 0) {
}
$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;
}

/**
* 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
*/
protected static function &convert($node) {
protected static function &convert($node, $callback = null) {
$output = array();

switch ($node->nodeType) {
Expand All @@ -102,9 +104,11 @@ protected 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)) {
Expand Down

0 comments on commit f3813a3

Please sign in to comment.