Comparison of three methods for generating XML files in PHP
There are three methods: Direct Writing; using DomDocument; using SimpleXML;
There are actually 4th types: XMLWriter, but I have never used it and I am too lazy to try it.
I want to see which of the three methods is faster.
Directly run the Code:
Copy codeThe Code is as follows:
Private function directWriteXml (& $ data ){
$ Xmltext = '<? Xml version = "1.0" encoding = "UTF-8"?> ';
$ Xmltext. = '<DocumentData> ';
$ Xmltext. = '<Detail> ';
$ Loop = count ($ data );
Foreach ($ data as $ d ){
$ Xmltext. = "<Row ID = \" {$ d ['id']} \ "Name = \" {$ d ['name']} \ "/> ";
}
$ Xmltext. = '</Detail> ';
$ Xmltext. = '</DocumentData> ';
Return $ xmltext;
}
Private function useDomDocument (& $ data ){
// Create an XML document and set the XML version and encoding ..
$ Dom = new DomDocument ('1. 0', 'utf-8 ');
// Create the root node
$ Detail01 = $ dom-> createElement ('detail ');
$ Dom-> appendchild ($ detail01 );
Foreach ($ data as $ d ){
$ Row = $ dom-> createElement ('row ', "ID = \" {$ d ['id']} \ "Name = \" {$ d ['name']} \ "");
$ Detail01-> appendchild ($ row );
}
Return $ dom-> saveXML ();
}
Private function useSimpleXML (& $ data ){
// Create an XML document and set the XML version and encoding ..
$ String = <XML
<? Xml version = '1. 0' encoding = 'utf-8'?>
<Detail01>
</Detail01>
XML;
$ Xml = simplexml_load_string ($ string );
Foreach ($ data as $ d ){
$ Xml-> addChild ('row ', "ID = \" {$ d ['id']} \ "Name = \" {$ d ['name']} \ "");
}
Return $ xml-> asXML ();;
}
A large number of cyclic operations are added for each call, and the time is recorded.
Copy codeThe Code is as follows:
$ Loop = 10000;
$ Xml = '';
Switch ($ _ GET ['id']) {
Case 1:
$ Ts = $ this-> microtime_float ();
For ($ I = 0; $ I <$ loop; $ I ++)
$ Xml = $ this-> directWriteXml ($ depdata );
$ Te = $ this-> microtime_float ();
$ T = $ te-$ ts;
$ This-> assign ('times ', $ t );
$ This-> assign ('method', 'Write directly ');
Break;
Case 2:
$ Ts = $ this-> microtime_float ();
For ($ I = 0; $ I <$ loop; $ I ++)
$ Xml = $ this-> useDomDocument ($ depdata );
$ Te = $ this-> microtime_float ();
$ T = $ te-$ ts;
$ This-> assign ('times ', $ t );
$ This-> assign ('method', 'domaindocument ');
Break;
Case 3:
$ Ts = $ this-> microtime_float ();
For ($ I = 0; $ I <$ loop; $ I ++)
$ Xml = $ this-> useSimpleXML ($ depdata );
$ Te = $ this-> microtime_float ();
$ T = $ te-$ ts;
$ This-> assign ('times ', $ t );
$ This-> assign ('method', 'simplexml ');
Break;
}
Echo $ xml;
As expected, the actual test results are the fastest to write directly, with only about 1/3 of the time consumed by other methods. The other two methods are similar, while SimpleXML is faster.