Skip to content

Instantly share code, notes, and snippets.

@yosko
Last active March 28, 2023 23:41
Show Gist options
  • Save yosko/6991691 to your computer and use it in GitHub Desktop.
Save yosko/6991691 to your computer and use it in GitHub Desktop.
Dom2Array converts a DOMDocument object to a PHP array. Array2Dom just does the opposite
<?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();
//list attributes
if($root->hasAttributes()) {
foreach($root->attributes as $attribute) {
$array['_attributes'][$attribute->name] = $attribute->value;
}
}
//handle classic node
if($root->nodeType == XML_ELEMENT_NODE) {
$array['_type'] = $root->nodeName;
if($root->hasChildNodes()) {
$children = $root->childNodes;
for($i = 0; $i < $children->length; $i++) {
$child = Dom2Array( $children->item($i) );
//don't keep textnode with only spaces and newline
if(!empty($child)) {
$array['_children'][] = $child;
}
}
}
//handle text node
} elseif($root->nodeType == XML_TEXT_NODE || $root->nodeType == XML_CDATA_SECTION_NODE) {
$value = $root->nodeValue;
if(!empty($value)) {
$array['_type'] = '_text';
$array['_content'] = $value;
}
}
return $array;
}
/**
* Recursive function to turn an array to a DOMDocument
* @param array $array the array
* @param DOMDocument $doc only used by recursion
*/
function Array2Dom($array, $doc = null) {
if($doc == null) {
$doc = new DOMDocument();
$doc->formatOutput = true;
$currentNode = $doc;
} else {
if($array['_type'] == '_text')
$currentNode = $doc->createTextNode($array['_content']);
else
$currentNode = $doc->createElement($array['_type']);
}
if($array['_type'] != '_text') {
if(isset($array['_attributes'])) {
foreach ($array['_attributes'] as $name => $value) {
$currentNode->setAttribute($name, $value);
}
}
if(isset($array['_children'])) {
foreach($array['_children'] as $child) {
$childNode = Array2Dom($child, $doc);
$childNode = $currentNode->appendChild($childNode);
}
}
}
return $currentNode;
}
?>
<?php
require_once "xmlutils.php";
$root = new DOMDocument('1.0', 'utf-8');
$root->load('user.xml');
$array = Dom2Array($root);
var_dump($array);
$newRoot = Array2Dom($array);
var_dump($newRoot->saveXML());
?>
<?xml version="1.0" encoding="utf-8"?>
<user id="1">
<updated timestamp="1381840191"/>
<login>login</login>
<password>password</password>
</user>
@dearsina
Copy link

Thank you for this. Made traversing the DOM of an XML file so much easier!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment