i needed to have an easy way to create a multi-dimensional but EXTREMELY SIMPLE php array out of some XML text i'm receiving. NOT an object. just an ARRAY.
i found that as simple a request as this seemed to be, the new (php5) DOM functions do not provide this functionality.
even the SimpleXML functions are object-oriented, which doesn't work for some of my purposes (sending to a Smarty template variable for looping through, etc.) -- returning attributes as SimpleXMLElement objects instead of strings, etc.. i just wanted an ARRAY containing the data as STRINGS.
eli () had submitted such code earlier, based on domxml/php4 calls. his function was called "domxml_xmlarray".
but when php5 came out, eli's comments at the bottom of the PHP site got erased. (fortunately, i had already saved his code.) no doubt, mine will too w/next version..
furthermore, as far as i can tell, no one has taken the cue to add something like eli's domxml_xmlarray function directly into the DOMDocument object (but it would be nice).
so i translated eli's code, now using the dom calls (instead of the older domxml calls), and renamed the function to "dom_to_simple_array()".
below is a script containing the function itself as well as an example of its use. just copy it to your server somewhere and execute it and it should work right off the bat if you are using php5.
thanks.
jeff stern
==================================================================
<?php
function dom_to_simple_array($domnode, &$array) {
$array_ptr = &$array;
$domnode = $domnode->firstChild;
while (!is_null($domnode)) {
if (! (trim($domnode->nodeValue) == "") ) {
switch ($domnode->nodeType) {
case XML_TEXT_NODE: {
$array_ptr['cdata'] = $domnode->nodeValue;
break;
}
case XML_ELEMENT_NODE: {
$array_ptr = &$array[$domnode->nodeName][];
if ($domnode->hasAttributes() ) {
$attributes = $domnode->attributes ();
if (!is_array ($attributes)) {
break;
}
foreach ($attributes as $index => $domobj) {
$array_ptr[$index] = $array_ptr[$domobj->name] = $domobj->value;
}
}
break;
}
}
if ( $domnode->hasChildNodes() ) {
dom_to_simple_array($domnode, $array_ptr);
}
}
$domnode = $domnode->nextSibling;
}
}
$strXMLData = "<contacts>
<contact>
<name>
John Doe
</name>
<phone>
123-456-7890
</phone>
</contact>
<contact>
<name>
Mary Smiley
</name>
<phone>
567-890-1234
</phone>
</contact>
</contacts>";
$domdoc = new DOMDocument;
$domdoc->loadXML($strXMLData);
$aData = array();
dom_to_simple_array($domdoc, $aData);
?><html>
<body>
<p>there are <? echo count($aData['contacts'][0]['contact']); ?>
contacts</p>
<p>the 2nd contact's phone number is
<?echo $aData['contacts'][0]['contact'][1]['phone'][0]['cdata']; ?>
</p>
<hr />
<p>Here is the raw array structure:</p>
<pre>
<? print_r($aData); ?>
</pre>
</body>
</html>