Archive for the ‘Uncategorized’ Category

Creating csv content

Friday, February 25th, 2011

It is tempting to simply generate CSV data with writing comma-separated  array-values.

implode(",", $data_array);

Unfortunately this obvious way of doing turns out to be a bad idea. Often it seems to be working at first, but eventually you’ll be faced with annoying bugs, wrongly escaped data.

Fortunately, PHP has a native function to write CSV values to a file.

fputcsv()

With a little trick you can use this function to write values to the screen.
Use the built-in streamwrappers:

 $outstream = fopen("php://output", 'w');
 fputcsv($outstream, $data_array, ',', '"');
 fclose($outstream);

This will echo the data to the screen.
Most people won’t know `php://output`. A pity it’s really powerful.

PHP memory leak

Wednesday, November 28th, 2007

Consider an RSS feed read in as an SimpleXMLobject $rss.

What’s the difference between:

foreach ($rss->channel as $channel) {
...
}

and
$foo = $rss->channel;
foreach ($foo as $channel) {
...
}

Not much you would say, the first code example is shorter and more to the point. However when putting the scripts to work, (with a big rss file) we’ll soon see the difference.

Memory problem and a growing swap file

After a while the former example is causing a lot of disk activity and you will see your swap file grow and grow, at my computer it reached the maximum of 4 GB and off course it took ages for the script to finish.

And all that while the maximum memory usage for a script is set to 24MB in php.ini. Should run in a 1G computer you would say.
Well example 2 does but example 1 does not!

Is seems that iterating over an object-property in a foreach loop is troubled by a memory leak.

Solution

Example 2 is the workaround!

Conclusion

PHP 5.1 until 5.2 seem to suffer from this memory leak.

Technorati Post

Wednesday, December 20th, 2006

Technorati Profile
No further use. 🙂

Your are browsing
the Archives of My Beloved PHP in the 'Uncategorized' Category.
Categories
Archives
Links