Convert arrays in PHP to XML format. Recently, the company has made an API interface. the output format must be JSON and XML. in PHP, the input JSON can be directly json_encode, but the output XML does not provide a function, so I decided to write it myself
Recently, the company has to create an API interface. the output format must be JSON and XML. in PHP, the input JSON can be directly json_encode, but the output XML does not provide a function, so I decided to write it myself.
FormatOutput = true ;} /*** convert the array to XML ** @ param array $ array the array to be converted * @ param string $ rootName the node name * @ param string $ version number * @ param string $ encodingXML encoding ** @ return string */public static function parse ($ array, $ rootName = 'root', $ version = '1. 0', $ encoding = 'utf-8') {self: init ($ version, $ encoding); // convert $ node = self: convert ($ array, $ rootName); self ::$ doc-> appendChild ($ node); return self ::$ doc-> SaveXML ();}/*** Recursive conversion ** @ param array $ array * @ param string $ nodeName node name ** @ return object (DOMElement) */private static function convert ($ array, $ nodeName) {if (! Is_array ($ array) return false; // create a parent node $ node = self: createNode ($ nodeName ); // loop array foreach ($ array as $ key => $ value) {$ element = self: createNode ($ key); // if it is not an array, the value of the created node, if (! Is_array ($ value) {$ element-> appendChild (self: createValue ($ value); $ node-> appendChild ($ element );} else {// if it is an array, recursion $ node-> appendChild (self: convert ($ value, $ key, $ element) ;}} return $ node ;} private static function createNode ($ name) {$ node = NULL; // if it is a string, create a node if (! Is_numeric ($ name) {$ node = self: $ doc-> createElement ($ name);} else {// if it is a number, create the default item node $ node = self: $ doc-> createElement ('ITEM');} return $ node ;} /*** create a text node ** @ param string | bool | integer $ value ** @ return object (DOMText | DOMCDATASection ); */private static function createValue ($ value) {$ textNode = NULL; // if it is bool type, convert to string if (true ===$ value | false ===$ value) {$ textNode = self: $ doc-> c ReateTextNode ($ value? 'True': 'false');} else {// if HTML tags are contained, create a CDATA node if (strpos ($ value, '<')>-1) {$ textNode = self ::$ doc-> createCDATASection ($ value);} else {$ textNode = self ::$ doc-> createTextNode ($ value );}} return $ textNode ;}}
Callback: In PHP, you can directly input JSON json_encode, but the output XML does not provide a function. Therefore, you have to write one by yourself...