Home > Article > Backend Development > How to convert xml to string in php
php method to convert xml to string: first create a php sample file; then define an "array2xml" method; finally use the foreach statement to convert php array to xml string.
Recommended: "PHP Video Tutorial"
php Convert xml string into array and convert array into xml;
1. Convert xml string into php array.
function xmlToArray($xml){ if (file_exists($xml)) { libxml_disable_entity_loader(false); $xml_string = simplexml_load_file($xml,'SimpleXMLElement', LIBXML_NOCDATA); }else{ libxml_disable_entity_loader(true); $xml_string = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA); } $result = json_decode(json_encode($xml_string),true); return $result; }
2. Convert php array to xml string
function array2xml($arr){ $str="<xml>"; foreach ($arr as $key=>$value){ $str.= "<$key>$value</$key>"; } $str.="</xml>"; return $str; }
The above is the detailed content of How to convert xml to string in php. For more information, please follow other related articles on the PHP Chinese website!