Creating XML with PHP - a view in mind

When creating XML in PHP, is it faster to create a string, then output the string, or use the XML functions that php provides? I am currently doing the following:

UPDATED for better code snippet:

$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;
}

}

Is there a faster way to create xml? I get about 2000 items, and it starts to slow down.

Thanks in advance!

+3
source share
5 answers

I don’t see you trying to avoid text before concatenating it. This means that sooner or later you are going to generate something that is almost - but not quite XML, and which will be rejected by any appropriate parser.

(XMLWriter, , , , XML PHP).

+2

xml. , , STRING .

, , , XML.

+6

SQL- , . , , 2000 .

, , - , JOIN.

-. , XMLWriter, , .

+1

( echo $xml while reset $xml ),

0

, , , .

, ,

$xml = '';
while ($row =  mysql_fetch_row($result))
{
    $xml .= '<items><test>' . implode('</test><test>', $row) . '</test></items>';
}

mysql_fetch_object() , .

, - :

$xml = '<items>';
while ($row =  mysql_fetch_assoc($result))
{
    $xml .= '<item>';
    foreach ($row as $k => $v)
    {
        $xml .= '<' . $k . '>' . htmlspecialchars($v) . '</' . $v . '>';
    }
    $xml .= '</item>';
}
$xml .= '</items>';

, , 100% , , "<" " > " "&". $k. script, , XML .

, , -. , , script? , 2000 . , -? ..

XML- PHP, XMLWriter, , , . , .

0

Source: https://habr.com/ru/post/1741320/


All Articles