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;