Example of converting php array to xml

Source: Internet
Author: User
Tags addchild zend

Example 1

The following multi-dimensional array is supported.

Test Code: test. php

<? Php
Include './ArrayToXML. Php ';
Header ('content-Type: text/XML ');
$ Data = array ("name" => "zhangsan", "sex" => "0", "address" => array ("sheng" => "chongqing ", "shi" => "nanchuan", "zhen" => "daguan "));
Echo ArrayToXML: toXml ($ data );

Processing code: ArrayToXML. php

<? Php

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 ("<? Xml version = '1. 0' encoding = 'utf-8'?> <$ 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 ();
 }
}
ArrayToXML. php comes from the network and I will not explain it any more.

Example 2

// Xml to array, including the root key, ignore empty elements and attributes, there are still major errors
Function xml_to_array ($ xml)
{
$ Reg = "/<(\ w +) [^>] *?> ([\ X00-\ xFF] *?) <\/\ 1> /";
If (preg_match_all ($ reg, $ xml, $ matches ))
    {
$ Count = count ($ matches [0]);
$ Arr = array ();
For ($ I = 0; $ I <$ count; $ I ++)
        {
$ Key = $ matches [1] [$ I];
$ Val = xml_to_array ($ matches [2] [$ I]); // recursion
If (array_key_exists ($ key, $ arr ))
            {
If (is_array ($ arr [$ key])
                {
If (! Array_key_exists (0, $ arr [$ key])
                    {
$ Arr [$ key] = array ($ arr [$ key]);
                    }
} Else {
$ Arr [$ key] = array ($ arr [$ key]);
                }
$ Arr [$ key] [] = $ val;
} Else {
$ Arr [$ key] = $ val;
            }
        }
Return $ arr;
} Else {
Return $ xml;
    }
}

// Convert Xml to an array, excluding the root key
Function xmltoarray ($ xml)
{
$ Arr = xml_to_array ($ xml );
$ Key = array_keys ($ arr );
Return $ arr [$ key [0];
}

Code
// Array selector similar to XPATH
Function xml_array_select ($ arr, $ arrpath)
{
$ Arrpath = trim ($ arrpath ,'/');
If (! $ Arrpath) return $ arr;
$ Self = 'XML _ array_select ';
   
$ Pos = strpos ($ arrpath ,'/');
$ Pos = $ pos? $ Pos: strlen ($ arrpath );
$ Curpath = substr ($ arrpath, 0, $ pos );
$ Next = substr ($ arrpath, $ pos );
   
If (preg_match ("/\ [(\ d +) \] $/", $ curpath, $ predicate ))
    {
$ Curpath = substr ($ curpath, 0, strpos ($ curpath, "[{$ predicate [1]}]");
$ Result = $ arr [$ curpath] [$ predicate [1];
} Else $ result = $ arr [$ curpath];
   
If (is_array ($ arr )&&! Array_key_exists ($ curpath, $ arr ))
    {
Die ('Key is not exists: '. $ curpath );
    }
   
Return $ self ($ result, $ next );
}

// If the input array is a full-number key, the element values are transmitted to $ callback in sequence; otherwise, the elements are transmitted to $ callback.
Function xml_array_each ($ arr, $ callback)
{
If (func_num_args () <2) die ('parameters error ');
If (! Is_array ($ arr) die ('parameter 1 shcould be an array! ');
If (! Is_callable ($ callback) die ('Parameter 2 shcould be an function! ');
$ Keys = array_keys ($ arr );
$ Isok = true;
Foreach ($ keys as $ key) {if (! Is_int ($ key) {$ isok = false; break ;}}
If ($ isok)
Foreach ($ arr as $ val) $ result [] = $ callback ($ val );
Else
$ Result [] = $ callback ($ arr );
Return $ result;
}

/**
* The simplest XML to array conversion
* @ Param string $ xmlstring XML string
* @ Return array XML array
*/
Function simplest_xml_to_array ($ xmlstring ){
Return json_decode (json_encode (array) simplexml_load_string ($ xmlstring), true );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.