In this article we will briefly explain how to use PHP to deal with the conversion between the array and XML.
PHP converts an array to XML
PHP can convert the array into xml format, the simple way is to traverse the array, and then the array of key / value into xml node, and then directly echo 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 next, the most simple, fast and fast, support for the array.
Another way is to use DOMDocument to generate 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.
PHP converts XML into an array
Do interface development often encounter someone else to submit to you is the xml format data, the common WeChat interface, Alipay interface, etc., their interface, such as sending messages are xml format, then we first find a way to get this Xml data, and then convert it into an array.
Suppose we get an XML like this:
<root>
<user>goocode</user>
<pvs>12345</pvs>
<ips>
<google_ip>1200</google_ip>
<bing_ip>1829</bing_ip>
</ips>
<date>2017-04-01</date>
</root>
Through simplexml_load_string () parsing read xml data, and then first converted to json format, and then converted into an array.
function xmlToArray($xml){
//Do not reference 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;
}
Call the function to get the array, we can carry out a variety of data processing.