Home  >  Article  >  Backend Development  >  Efficiency comparison of three methods for generating xml files in php

Efficiency comparison of three methods for generating xml files in php

WBOY
WBOYOriginal
2016-07-25 09:08:15966browse
  1. private function directWriteXml(&$data){
  2. $xmltext='';
  3. $xmltext .= '';
  4. $xmltext .='';
  5. $loop=count($data);
  6. foreach ($data as $d){
  7. $xmltext .=" ";
  8. }
  9. $xmltext .='';
  10. $xmltext .=' ';
  11. return $xmltext;
  12. }
  13. private function useDomDocument(&$data){
  14. // Create an XML document and set the XML version and encoding. .
  15. $dom=new DomDocument('1.0', 'utf-8');
  16. // Create root node
  17. $detail01 = $dom->createElement('Detail');
  18. $dom->appendchild($detail01 );
  19. foreach ($data as $d) {
  20. $row = $dom->createElement('Row'," ID=" {$d['id']} " Name=" {$d['name ']}" " );
  21. $detail01->appendchild($row);
  22. }
  23. return $dom->saveXML();
  24. }
  25. private function useSimpleXML(&$data){
  26. // Create an XML Document and set XML version and encoding. .
  27. $string = <<
  28. XML;
  29. $xml = simplexml_load_string ($string);
  30. foreach ($data as $d) {
  31. $xml->addChild('Row'," ID=" {$d['id']} " Name=" {$d['name ']}" " );
  32. }
  33. return $xml->asXML(); ;
  34. }
  35. ?>
Copy code

When calling, add a large number of loop operations to each one, and record the time .

  1. $loop=10000;
  2. $xml='';
  3. switch($_GET['id']){
  4. case 1:
  5. $ts=$this->microtime_float( );
  6. for( $i=0; $i<$loop; $i++)
  7. $xml=$this->directWriteXml($depdata);
  8. $te=$this->microtime_float();
  9. $t =$te-$ts;
  10. $this->assign('times',$t);
  11. $this->assign('method','write directly');
  12. break;
  13. case 2:
  14. $ ts=$this->microtime_float();
  15. for( $i=0; $i<$loop; $i++)
  16. $xml=$this->useDomDocument($depdata);
  17. $te=$this- >microtime_float();
  18. $t=$te-$ts;
  19. $this->assign('times',$t);
  20. $this->assign('method','DomDocument');
  21. break;
  22. case 3:
  23. $ts=$this->microtime_float();
  24. for( $i=0; $i<$loop; $i++)
  25. $xml=$this->useSimpleXML($depdata) ;
  26. $te=$this->microtime_float();
  27. $t=$te-$ts;
  28. $this->assign('times',$t);
  29. $this->assign('method ','SimpleXML');
  30. break;
  31. }
  32. echo $xml;
  33. ?>
Copy code

Actual test results: Direct writing is the fastest, and the time consumption is only about 1/3 of other methods. The other two methods are almost the same, and SimpleXML is faster in comparison.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn