note 52761 added to ref.simplexml

From: Date: Thu, 12 May 2005 00:18:39 +0000
Subject: note 52761 added to ref.simplexml
Groups: php.notes 
Request: Send a blank email to php-notes+get-89290@lists.php.net to get a copy of this message
After much hair pulling, I have created a function that allows you work with your XML data as a standard object (stdClass), rather than doing all kinds of iterations and element type-casting. It makes comparision of values and data MUCH easier. NOTE: If any attributes() tags exist, you will lose them in the conversion. Keep a copy of your SimpleXML object before conversion if you need the attribute data! Also note that SimpleXML objects cannot be serialized and then unserialized, so this function is uni-directional. Example: config.xml --------- <?xml version='1.0' encoding="ISO-8859-1"?> <CONFIG> <DATABASE> <SERVER>localhost</SERVER> <USER>user</USER> <PASSWD>password</PASSWD> <DATABASE>MyDatabase</DATABASE> </DATABASE> </CONFIG> --------- config.php --------- <?php /** * @return void * @param variable $obj * @param class $class_type * @desc Takes a variable and converts it to an object of class $class_type */ function ClassTypeCast(&$obj,$class_type){ if(class_exists($class_type,true)){ $obj=unserialize( $toreplace="/(^|;)*O:[0-9]+:\"[^\"]+\":/i"; preg_replace($toreplace,"\\1"."O:" . strlen($class_type).":\"" . $class_type."\":", serialize($obj)) ); } } $xmlfile='config.xml'; $CONFIG=simplexml_load_file($xmlfile); ClassTypeCast($CONFIG,'stdClass'); //no need to type cast if($CONFIG->DATABASE->SERVER=='localhost') echo "It Works!!!"; ?> --------- ---- Manual Page -- http://www.php.net/manual/en/ref.simplexml.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+52761 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52761&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52761&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52761&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52761&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52761&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+52761&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#89290) next »