Today, the project needs to generate xml logs. There are many types of logs, and I wrote them myself. At the end of the process, it was a bit laborious. Post them and share them. If there are any errors, please correct them:
Test data:
$ DATA = array ('books ', array ('book ',
Array ('bookname', 'ordinary World '),
Array ('author', 'luyao '),
Array ('pubdate', 'August 11 '),
Array ('info', array ('name' => 'about'), 'won the third Chinese Mao Dun literature Award in the ordinary world in March 1991 '),
), Array ('book ',
Array ('bookname', 'aliyun '),
Array ('author', 'yu hua '),
Array ('pubdate', 'August 11 '),
Array ('info', array ('name' => 'about'), 'directed by Zhang Yimou in 1994, starring Ge You and Gong Li ')
)
);
/**
* Create a log XML file
*
* @ Param $ source data of the XML generated by data array
*
* Data Format definition constraints:
* 1. the layers of data nodes must be consistent with those of XML nodes.
* 2. the node attribute must be at the same level as the node, but the node appears as the first element, and the attribute node appears as the successor element.
*
* Demo: array ('installationlog ',
* Array ('hostip', array (), '192. 168.1.107 '),
* Array ('computername', array (), 'bglwzw5nlxh5luwx '),
* Array ('orderid', array (), 'r0rbwi04mtvtltuwotktm1jsra = '),
* Array ('userdata', array ('name' => 'softwareid'), '0 '),
* Array ('logtype', array (), '0 '),
* Array ('time', array (), '2017-06-13 18:14:46 '),
* Array ('utcms ', array (), '123 ')
*)
*
* <? XML version = "1.0" encoding = "UTF-8"?>
* <Installationlog>
* <Hostip> 192.168.1.107 * <Computername> bglwzw5nlxh5luwx </computername>
* <Orderid> r0rbwi04mtvtltuwotktm1jsra ==</orderid>
* <Userdata name = "softwareid"> 0 </userdata>
* <Logtype> 0 </logtype>
* <Time> 18:14:46 </time>
* <UTF-8> 1402654506172 </utcms>
* </Installationlog>
*
* @ Return string: XML file generated
*/
Function createlogxmlfile (array $ data, $ isonlyroot = false ){
Static $ XML;
Static $ outerlen = 0;
Static $ COUNT = 0;
If (! $ XML ){
$ Xml = new xmlwriter ();
$ XML-> openmemory ();
$ XML-> setindentstring ('');
$ XML-> setindent (true );
$ XML-> startdocument ('1. 0', 'utf-8 ');
}
$ Length = count ($ data );
If ($ outerlen = 0 ){
$ Outerlen = $ length;
}
For ($ I = 0; $ I <$ length; $ I ++ ){
If (is_array ($ data [$ I]) & $ data ){
If (count ($ data [$ I]) === 1 ){
$ Attr_n = array_shift (array_keys ($ data [$ I]);
$ Attr_v = array_shift (array_values ($ data [$ I]);
$ XML-> writeattribute ($ attr_n, $ attr_v );
} Else {
Createlogxmlfile ($ data [$ I]);
}
} Else {
If ($ I = 0 ){
$ XML-> startelement ($ data [$ I]);
} Else {
$ XML-> text ($ data [$ I]);
}
}
If ($ I ===$ length-1 ){
If ($ isonlyroot ){
$ XML-> endelement ();
$ XML-> enddocument ();
Return $ XML-> outputmemory (false );
} Else {
If (is_array ($ data [$ I]) {
$ Count ++;
If ($ count ===$ outerlen ){
$ XML-> enddocument ();
Return $ XML-> outputmemory (false );
}
}
$ XML-> endelement ();
}
}
}
}