Petrogad
Petrogad

Reputation: 4423

PHP Increasing write to page speed

I'm currently writing out xml and have done the following:

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

$xml being the xml to be written out. I'm near about 1.8 megs of text (which I found via firebug), it seems as the writing is taking more time than the script to run.. is there a way to increase this write speed?

Thank you in advance.

Upvotes: 2

Views: 201

Answers (3)

icio
icio

Reputation: 3138

It might be worth trying dumping your XML to a temporary file and then using readfile to send the data to the user.

Upvotes: 0

Mathew
Mathew

Reputation: 8279

Google's results seem to suggest that echo has poor performance for large strings. One solution would be to break the string to be echo'd into chunks;

function echobig($string, $bufferSize = 8192)
{
    $splitString = str_split($string, $bufferSize);

    foreach($splitString as $chunk)
        echo $chunk;
}

Please note, I've not tested this code out; I found it in the php docs. Read this blog post for someone else who had a similar issue that was solved by splitting the echo string into chunks.

Upvotes: 0

pestilence669
pestilence669

Reputation: 5701

It really depends on how you're writing the data. If you're using DOM, consider XMLWriter. It's a bit faster and more streamlined.

If you're homebrewing your XML output, ensure that you aren't appending strings unnecessarily. For instance:

echo "<tag>" . $data . "</tag>"; // this is slower
echo '<tag>', $data, '</tag>';   // this is faster

The comma operator doesn't create new strings. Also to consider, single quoted strings are slightly faster than double quotes. There is no variable substitution to scan for. Normally, the difference is minimal, but in a tight loop you can definitely see it.

Depending on your data source and how you construct your XML, your processing might be the bottleneck. Try profiling with xdebug and seeing where your bottlenecks actually are.

Upvotes: 2

Related Questions