'How to generate CSV file under 3 MB [closed]

i've been wondering how to generate a CSV file from array and keep it under certain size. Can someone show me how to do it?

do
    {      
        $fp = fopen($file, 'a');  
            
        fputcsv($fp, generateArray(30));  

        fclose($fp);
        $filesize = round(filesize($file) / 1024 / 1024, 2); // megabytes with 2 digit
    
        echo "Chars.csv ".$filesize ;

    }while($filesize < 1); //in MB
php


Solution 1:[1]

thank you for your attention. clearstatcache() solved the issue

do
    {      
        fputcsv($fp, generateArray(30));  
        
        $filesize = round(filesize($file) / 1024 / 1024, 2); // megabytes with 2 digit
    
        clearstatcache();

    }while($filesize < 3); //in MB

Solution 2:[2]

It isn't practical to use the printable size for calculations. Plus you don't need to ask the filesystem for information you're generating yourself. Putting that together:

$fp = fopen($file, 'a');
$filesize = 0;
do {
    $filesize += fputcsv($fp, generateArray(30));
    echo $file, ' ', round($filesize / 1024 / 1024, 2), "MB\n";
} while ($filesize < 1048576); // 1 MB
fclose($fp);

We are, however, missing a detail. We check size after writing, thus we'll always overflow the limit. If this is important, we can't really use fputcsv(). We need an alternative mechanism were we can generate a line in advance and then decide if it'll get included. It isn't too difficult to generate CSV manually, but I can also think of having a secondary stream like fopen('php://memory', 'w'); to insert individual lines for size checks only and get it removed afterwards.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Muhammad Luqman Md Khir
Solution 2 Álvaro González