Home > php教程 > php手册 > PHP中3种生成XML文件方法的速度效率比较

PHP中3种生成XML文件方法的速度效率比较

WBOY
Release: 2016-06-13 11:57:33
Original
865 people have browsed it

PHP中3种生成XML文件方法的速度比较
有3种方法,分别是直接写;使用DomDocument;使用SimpleXML;
其实还有第4种:使用XMLWriter,不过我没用过,也懒得试了.
主要是想看看这3种方式哪个速度要快些
直接上代码:

复制代码 代码如下:


private function directWriteXml(&$data){
  $xmltext='';
  $xmltext .='';
  $xmltext .='';
  $loop=count($data);
  foreach ($data as $d){
   $xmltext .=" ";
  }
  $xmltext .='
';
  $xmltext .='
';
  return $xmltext;
 }
 private function useDomDocument(&$data){
  //  创建一个XML文档并设置XML版本和编码。。
  $dom=new DomDocument('1.0', 'utf-8');
  //  创建根节点
  $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){
  //  创建一个XML文档并设置XML版本和编码。。
  $string =


XML;
  $xml = simplexml_load_string($string);
  foreach ($data as $d) {
      $xml->addChild('Row'," ID=\" {$d['id']} \"  Name=\" {$d['name']}\" " );
  }
  return $xml->asXML(); ;
 }


调用时每个都加上大数循环操作,并记录时间

复制代码 代码如下:


 $loop=10000;
  $xml='';
  switch($_GET['id']){
   case 1:
     $ts=$this->microtime_float();
     for( $i=0; $i      $xml=$this->directWriteXml($depdata);
     $te=$this->microtime_float();
     $t=$te-$ts;
     $this->assign('times',$t);
     $this->assign('method','直接写');
     break;
   case 2:
     $ts=$this->microtime_float();
     for( $i=0; $i      $xml=$this->useDomDocument($depdata);
     $te=$this->microtime_float();
     $t=$te-$ts;
     $this->assign('times',$t);
     $this->assign('method','DomDocument');
     break;
   case 3:
     $ts=$this->microtime_float();
     for( $i=0; $i      $xml=$this->useSimpleXML($depdata);
     $te=$this->microtime_float();
     $t=$te-$ts;
     $this->assign('times',$t);
     $this->assign('method','SimpleXML');
     break;
  }
  echo $xml;


实测结果不出所料,直接写最快,耗时只有其他方式的1/3左右. 而其他2种方法差不多,相比之下SimpleXML要快一些.
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template