title: Building XML with PHP - Performance in mind
body: <p>When building XML in PHP, is it quicker to build a string, then echo out the string or to use the XML functions that php gives you? Currently I'm doing the following:</p>
  
  <p>UPDATED to better code snippet: </p>
  
  <pre><code>$searchParam = mysql_real_escape_string($_POST['s']);
  $search = new Search($searchParam);
  
  if($search-&gt;retResult()&gt;0){
      $xmlRes = $search-&gt;buildXML();
  }
  else {
      $xmlRes = '&lt;status&gt;no results&lt;/status&gt;';
  }
  
  $xml = "&lt;?xml version=\"1.0\"?&gt;";
  $xml.="&lt;results&gt;";
  $xml.=$xmlRes;
  $xml.="&lt;/results&gt;"
  
  header ("content-type: text/xml");
  header ("content-length: ".strlen($xml));
  echo($xml);
  
  
  class Search {
  private $num;
  private $q;
  
  function __construct($s){
      $this-&gt;q = mysql_query('select * from foo_table where name = "'.$s.'"');
      $this-&gt;num = mysql_num_rows($this-&gt;q);
  }
  
  function retResult(){
      return $this-&gt;num;
  }
  
  function buildXML(){
      $xml ='&lt;status&gt;success&lt;/status&gt;';
      $xml.='&lt;items&gt;';
      while($row = mysql_fetch_object($this-&gt;q)){
          $xml.='&lt;item&gt;';
          $desTag = '&lt;info&gt;&lt;![CDATA[';
          foreach ($row as $key =&gt; $current){
              if($key=='fob'){
                  //do something with current
                  $b = mysql_query('select blah from dddd where id ='.$current);
                  $a = mysql_fetch_array($b);
                  $xml.='&lt;'.$key.'&gt;'.$a['blah'].'&lt;/'.$key.'&gt;';
              }
              else if($key =='this' || $key=='that'){
                  $desTag = ' '.$current;
              }
              else {
                  $xml.='&lt;'.$key.'&gt;'.$current.'&lt;/'.$key.'&gt;';
              }   
          }
          $desTag.= ']]&gt;&lt;/info&gt;';
          $xml.=$desTag;
          $xml.='&lt;/item&gt;';
      }
      $xml.='&lt;/items&gt;';
      return $xml;
  }
  
  }
  </code></pre>
  
  <p>Is there a faster way of building the xml? I get to about 2000 items and it starts to slow down..</p>
  
  <p>Thanks in advance!</p>