note 52764 deleted from ref.dom by didou
| From: | didou@php.net | Date: | Mon, 13 Mar 2006 00:02:38 +0000 |
| Subject: | note 52764 deleted from ref.dom by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-105399@lists.php.net to get a copy of this message | ||
Note Submitter: toma at smartsemantics dot com
----
Based loosely on some previously provided examples, here are 2 functions to read in an XML file
using DOM and parse it into a usable array for reading/access. The output is a very clean array.
------------------------------------
function LoadXMLFile( $path,$file) {
$oldpath= getcwd( ) ;
chdir( $path) ;
$dom= DOMDocument::load( $path.$file) ;
chdir( $oldpath) ;
$xml= array( ) ;
parseXML( $dom,$xml) ;
return $xml;
}
function parseXML( $dom,&$arr)
{
$arr_ptr= &$arr;
$dom= $dom->firstChild;
while( !is_null( $dom) ) {
switch ( $dom->nodeType) {
case XML_TEXT_NODE:
if( trim( $dom->nodeValue) != '') {
if( is_array( $arr_ptr) ) {
$arr_ptr[]= $dom->nodeValue;
}
elseif( $arr_ptr != '') {
$arr_ptr= array( $arr_ptr) ;
$arr_ptr[]= $dom->nodeValue;
}
else{
$arr_ptr= $dom->nodeValue;
}
}
break;
case XML_ELEMENT_NODE:
$arr_ptr= &$arr[$dom->nodeName];
if ( $dom->hasAttributes( ) ) {
$attributes= $dom->attributes;
foreach( $attributes as $index= >$domobj) {
$arr_ptr['ATTRIBUTES'] [$domobj->name]= $domobj->value;
}
}
break;
}
if( $dom->hasChildNodes( ) ) {
parseXML( $dom,$arr_ptr) ;
}
$dom= $dom->nextSibling;
}
}
------------------------------------
Example usage:
$CONFIG= LoadXMLFile( '/var/www/html/site.com/php-bin/','config.xml') ;