Convert the array into an XML string-PHP

Source: Internet
Author: User

I:Code:

 

// ************************** test ****** * *******************
$ vararray = array (
"name" => array (" alen ", "Andy", "Tom"),
"cuntry" => array ("China", "Japan", "English "),
"Number" => array (1, 2, 3, array (11, 22, 33)
);
$ pp = toxml ($ vararray, "gb2312");
echo $ pp;

/**
* convert the given array into an XML string
* @ author [yans@tks-it.com.cn]
* @ Param $ Arrays: array to be converted
* @ Param $ encoding: encoding of the XML file
* @ return string
*/
function toxml ($ arrays, $ encoding = '')
{< br> // array detection
If (! Is_array ($ arrays)
{< br> echo " $ arrays is not a array! ";
return false;
}< br> $ xmlstr = '';
// XML file encoding Settings
if ($ encoding = '')
{< br> $ xmlstr. = ' ';
}< br> else
{< br> $ xmlstr. =' $ xmlstr. = $ encoding;
$ xmlstr. ='"?> ';
}< br> $ xmlstr. = ' ';
// call the array traversal function
$ xmlstr. = traversal ($ arrays);
$ xmlstr. = ' ';
return $ xmlstr;
}

/**
* Traverses the array to form an XML fragment string.
*
* @ Author [yans@tks-it.com.cn]
* @ Param $ arr: array to be traversed
* @ Return string
*/
Function traversal ($ ARR)
{
$ Arrstring = '';
While ($ newarr = each ($ ARR ))
{
$ Arrstring. = "<$ newarr [0]> ";
If (is_array ($ newarr [1])
{
$ Tempstring = traversal ($ newarr [1]);
$ Arrstring. = $ tempstring;
}
Else
{
$ Arrstring. = "$ newarr [1]";
}
$ Arrstring. = "</$ newarr [0]> ";
}
Return $ arrstring;
}
?>

Ii. execution results: (the results have been manually adjusted to facilitate observation)

 

<? XML version = "1.0" encoding = "gb2312"?>
<Root>
<Name>
<0> Alen </0>
<1> Andy </1>
<2> Tom </2>
</Name>

<Cuntry>
<0> China </0>
<1> Japan </1>
<2> English </2>
</Cuntry>

<Number>
<0> 1 </0>
<1> 2 </1>
<2> 3 </2>
<3>
<0> 11 </0>
<1> 22 </1>
<2> 33 </2>
</3>
</Number>

</Root>

Iii. Notes:

Note: XML labels start with underscores (_) and cannot contain strings with the words "XML!

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.