在 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/