I'm creating a system to generate sitemaps for a application I'm working on, and one of the requirements for generating sitemaps is that each sitemap shouldn't have a file size greater than 10mb (10,485,760 bytes) as can be seen here.
This is my code to create the sitemap:
$fp = fopen($this->getSitemapPath() . $filename, 'w');
fwrite($fp, $siteMap->__toString());
fclose($fp);
The method $siteMap->__toString()
holds a maximum of 50000 links.
Is there a way to check the resulting file size before calling the function fwrite
?
Sure, you can use mb_strlen
to get the length of your string before you write it out to a file.
$contents = $siteMap->__toString();
if(mb_strlen($contents, '8bit') >= 10485760) {
echo "Oops, this is too big";
} else {
fwrite($fp, $contents);
}