php - 使用 PHP 构建 XML - 考虑性能

标签 php xml performance

在 PHP 中构建 XML 时,构建字符串然后回显字符串或使用 php 提供的 XML 函数更快吗?目前我正在做以下事情:

已更新为更好的代码片段:

$searchParam = mysql_real_escape_string($_POST['s']);
$search = new Search($searchParam);

if($search->retResult()>0){
    $xmlRes = $search->buildXML();
}
else {
    $xmlRes = '<status>no results</status>';
}

$xml = "<?xml version=\"1.0\"?>";
$xml.="<results>";
$xml.=$xmlRes;
$xml.="</results>"

header ("content-type: text/xml");
header ("content-length: ".strlen($xml));
echo($xml);


class Search {
private $num;
private $q;

function __construct($s){
    $this->q = mysql_query('select * from foo_table where name = "'.$s.'"');
    $this->num = mysql_num_rows($this->q);
}

function retResult(){
    return $this->num;
}

function buildXML(){
    $xml ='<status>success</status>';
    $xml.='<items>';
    while($row = mysql_fetch_object($this->q)){
        $xml.='<item>';
        $desTag = '<info><![CDATA[';
        foreach ($row as $key => $current){
            if($key=='fob'){
                //do something with current
                $b = mysql_query('select blah from dddd where id ='.$current);
                $a = mysql_fetch_array($b);
                $xml.='<'.$key.'>'.$a['blah'].'</'.$key.'>';
            }
            else if($key =='this' || $key=='that'){
                $desTag = ' '.$current;
            }
            else {
                $xml.='<'.$key.'>'.$current.'</'.$key.'>';
            }   
        }
        $desTag.= ']]></info>';
        $xml.=$desTag;
        $xml.='</item>';
    }
    $xml.='</items>';
    return $xml;
}

}

是否有更快的构建 xml 的方法?我得到大约 2000 个项目,它开始变慢..

提前致谢!

最佳答案

使用 xml 解析器。请记住,当您连接一个字符串时,您必须在每次连接时重新分配整个字符串。

对于小字符串,字符串可能更快,但在您的情况下肯定使用 XML 函数。

关于php - 使用 PHP 构建 XML - 考虑性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2647438/

相关文章:

performance - Julia (Julia-lang) 性能与 Fortran 和 Python 的比较

php - HTTP 转义字符、PHP、CALDAV

java - Camel XML路由: can I give a "uri" attribute in a <from> element the value of a Java constant?

xml - golang - 提取 xml 字符串中的元素

php - XMLA解析获取多个属性

PHP - 复制或不复制,这是变量?

c++ - 如何查找无序数(线性搜索)

PHP - 是否可以使用 PHP 从图像列表创建视频(任何格式)?

php - 日期时间格式和时区

php - 替换两个字符之间的每个实例