In development, we often encounter the conversion between arrays and XML, especially when processing interface development, such as the other client post an XML format data to the server, the server's program is responsible for receiving the resolution, There is also the need to provide data table data in XML format to third parties and so on applications.
In this article we will briefly describe how to use PHP to process the conversion between arrays and XML.
SOURCE download: The conversion between PHP arrays and XML
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:
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:
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:
<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.
function Xmltoarray ($xml) {
//prohibit referencing of external XML entity
Libxml_disable_entity_loader (true);
$xmlstring = simplexml_load_string ($xml, ' simplexmlelement ', libxml_nocdata);
$val = Json_decode (Json_encode ($xmlstring), true);
return $val;
}
Call Xmltoarray () to get the following results:
After we get the array, we can do a variety of processing of the data.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.