Php array converted to xml code
- Class ArrayToXML
- {
- /**
- * The main function for converting to an XML document.
- * Pass in a multi dimen1_array and this recrusively loops through and builds up an XML document.
- *
- * @ Param array $ data
- * @ Param string $ rootNodeName-what you want the root node to be-defaultsto data.
- * @ Param SimpleXMLElement $ xml-shoshould only be used recursively
- * @ Return string XML
- */
- Public static function toXml ($ data, $ rootNodeName = 'data', $ xml = null)
- {
- // Turn off compatibility mode as simple xml throws a wobbly if you don't.
- If (ini_get ('zend. zemo-compatibility_mode ') = 1)
- {
- Ini_set ('zend. zemo-compatibility_mode ', 0 );
- }
- If ($ xml = null)
- {
- $ Xml = simplexml_load_string (" <$ RootNodeName/> ");
- }
- // Loop through the data passed in.
- Foreach ($ data as $ key => $ value)
- {
- // No numeric keys in our xml please!
- If (is_numeric ($ key ))
- {
- // Make string key...
- $ Key = "unknownNode _". (string) $ key;
- }
- // Replace anything not alpha numeric
- $ Key = preg_replace ('/[^ a-z]/I', '', $ key );
- // If there is another array found recrusively call this function
- If (is_array ($ value ))
- {
- $ Node = $ xml-> addChild ($ key );
- // Recrusive call.
- ArrayToXML: toXml ($ value, $ rootNodeName, $ node );
- }
- Else
- {
- // Add single node.
- $ Value = htmlentities ($ value );
- $ Xml-> addChild ($ key, $ value );
- }
- }
- // Pass back as string. or simple xml object if you want!
- Return $ xml-> asXML ();
- }
- }
2. code for converting php array to xml written by myself
- Function arrtoxml ($ arr, $ dom = 0, $ item = 0 ){
- If (! $ Dom ){
- $ Dom = new DOMDocument ("1.0 ");
- }
- If (! $ Item ){
- $ Item = $ dom-> createElement ("root ");
- $ Dom-> appendChild ($ item );
- }
- Foreach ($ arr as $ key => $ val ){
- $ Itemx = $ dom-> createElement (is_string ($ key )? $ Key: "item ");
- $ Item-> appendChild ($ itemx );
- If (! Is_array ($ val )){
- $ Text = $ dom-> createTextNode ($ val );
- $ Itemx-> appendChild ($ text );
- } Else {
- Arrtoxml ($ val, $ dom, $ itemx );
- }
- }
- Return $ dom-> saveXML ();
- }
- ?>
|