Examples of transformations between PHP arrays and XML

Source: Internet
Author: User
Tags foreach addchild arrays numeric json zend

PHP converts an array to XML

PHP can convert an array to an XML format by traversing the array and then converting the key/value of the array into an XML node, and then directly echo the output, such as:

  code is as follows copy code

function Arraytoxml ($arr) {
    $xml = "<root>";
    foreach ($arr as $key => $val) {
        if Is_array ($ val)) {
            $xml. = "<". $key. " > ". Arraytoxml ($val)." </". $key." > ";
       }else{
             $xml. = "<". $key. " > ". $val." </". $key." > ";
       }
   }
    $xml. = "</root>";
    return $xml;
}

I tested the following, this is the simplest, faster, support more than the number of groups, Chinese will not garbled.

Another approach is to use DOMDocument to generate the XML structure:

The code is as follows Copy Code

function Arraytoxml ($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 {
Arraytoxml ($val, $dom, $ITEMX);
}
}
return $dom->savexml ();
}

It can also convert an array to XML and support multidimensional arrays, and the resulting XML Chinese is not garbled.

PHP converts XML to an array

Do interface development often encounter other people submitted to you are XML format data, common micro-letter interface, Alipay interface, and so on, their interface such as sending message communication are XML format, then we first find a way to get the XML data, and then convert it into an array.
Let's say we get one of these xml:

The code is as follows Copy Code

<root>
<user> Moonlight Light Abcd</user>
<pvs>13002</pvs>
<ips>
<baidu_ip>1200</baidu_ip>
<google_ip>1829</google_ip>
</ips>
<date>2016-06-01</date>
</root>

The XML data is read by simplexml_load_string (), and then the array is converted to JSON format.

The code is as follows Copy Code
function Xmltoarray ($xml) {
Prohibit referencing external XML entities
Libxml_disable_entity_loader (TRUE);
$xmlstring = simplexml_load_string ($xml, ' simplexmlelement ', libxml_nocdata);
$val = Json_decode (Json_encode ($xmlstring), true);
return $val;
}

After we get the array, we can do a variety of processing of the data.

Below is the online

The code is as follows Copy Code

Class Arraytoxml
{
/**
* The main function for converting to an XML document.
* Pass in a multi dimensional array and the recrusively loops through and builds up an XML document.
*
* @param array $data
* @param string $rootNodeName-what your want the root node to Be-defaultsto data.
* @param simplexmlelement $xml-should 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.ze1_compatibility_mode ') = = 1)
{
Ini_set (' Zend.ze1_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 the 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 is back as String. or simple XML object if you want!
return $xml->asxml ();
}
}

Here's the code I edited myself.

The code is as follows Copy Code

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 ();
}

XML to Array

  code is as follows copy code

If you use curl Gets the XML data
$xml = simplexml_load_string ($data);
$data [' tk '] = Json_decode (Json_encode ($xml), TRUE);

$xml = simplexml_load_file ($data)
$data [' tk '] = Json_decode (Json_encode ($xml), TRUE) If the URL data is obtained directly;
First The SimpleXML object is converted to JSON and the JSON is converted to an array.

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.