Yosko's snippets

Snippets gathered around the web



CSS 2 CSharp 1 HTML 2 Javascript 2 PHP 12 XML 1 color 2 image 1 security 2

.

XML

Dom2Array + Array2Dom

<?php
 
/**
* Recursive function to turn a DOMDocument element to an array
* @param DOMDocument $root the document (might also be a DOMElement/DOMNode?)
*/
function Dom2Array($root) {
    $array = array();
     
    if($root->hasAttributes()) {
        foreach($root->attributes as $attribute) {
            $array['_attributes'][$attribute->name] = $attribute->value;
        }
    }
    if($root->hasChildNodes()) {
        $children = $root->childNodes;
        if($children->length == 1
            && ($children->item(0)->nodeType == XML_TEXT_NODE
            || $children->item(0)->nodeType == XML_CDATA_SECTION_NODE)
        ) {
            $array['_value'] = $children->item(0)->nodeValue;
        } else {
            for($i = 0; $i < $children->length; $i++) {
                if($children->item($i)->nodeType == XML_ELEMENT_NODE) {
                    $child = $children->item($i);
                    $array['_children'][$child->nodeName] = Dom2Array($child);
                }
            }
        }
    }
    return $array;
}
 
/**
* Recursive function to turn an array to a DOMDocument
* @param array $array the array
* @param string $name only used by recursion
* @param DOMDocument $doc only used by recursion
*/
function Array2Dom($array, $name = '', $doc = null) {
    //current node
    if($doc == null) {
        $doc = new DOMDocument();
        $doc->formatOutput = true;
        $currentNode = $doc;
    } else {
        $currentNode = $doc->createElement($name);
    }
     
    //children/attributes/values of current node
    foreach($array as $key => $value) {
        if($key == '_value') {
            $currentNode->nodeValue = $value;
        } elseif($key == '_attributes') {
            foreach($value as $name => $attribute) {
                $currentNode->setAttribute($name, $attribute);
            }
        } elseif($key == '_children') {
            foreach($value as $name => $child) {
                $childNode = Array2Dom($child, $name, $doc);
                $childNode = $currentNode->appendChild($childNode);
            }
        }
    }
     
    return $currentNode;
}
 
?>

PHP XML

https://gist.github.com/yosko/6991691

<iframe width="100%" height="1424" src="http://snip.yosko.net/index.php?embed=525d460027f5b" type="text/html"></iframe>

Text only - Permalink - Snippet public post date 12/05/2015

This page's Feed


Yosko's snippets 1.84 by Bronco - generated in 0.008 s