Reputation: 914
again. First of all, bear with me, it's late at night, and I'm tired, so this is probably a simple answer...
I'm gathering info on products, one by one, then writing each product as a line in a CSV file. However, I don't want one huge CSV file, so I'm trying to split the files up by size. As each new product is gathered, the script should check whether or not the file it's about to write to is less than the limit. If it is, then it should go ahead and write to that file. If not, then a new file should be created and the product added to the new file.
Here's what I curently have trying to limit the size of the file:
$f = 1;
if(file_exists($shop_path.'items/items'.$f.'.txt'))
{
if(filesize($shop_path.'items/items'.$f.'.txt') >= 512000)
{
$f++;
$fh = fopen($shop_path.'items/items'.$f.'.txt', "a+");
}
else
{
$fh = fopen($shop_path.'items/items'.$f.'.txt', "a+");
}
}
else
{
$fh = fopen($shop_path.'items/items'.$f.'.txt', "a+");
}
if(fwrite($fh, $prod_str) === TRUE)
{
echo 'Done!<br />';
}
else
{
echo 'Could not write to file<br />';
}
fclose($fh);
However, I just keep getting the "Could not write to file" error. Why is this?
Upvotes: 1
Views: 1840
Reputation: 212412
The ftell() function will always tell you your current byte offset in a file. Test the value of this before each write, and if it's over your predefined value then you can close that file and open a new one.
Upvotes: 2
Reputation: 9030
fwrite doesnt return a boolean value, only on failure (false).
"fwrite() returns the number of bytes written, or FALSE on error."
Check out: http://hu2.php.net/manual/en/function.fwrite.php
Maybe it works:
if(fwrite($fh, $prod_str))
{
echo 'Done!<br />';
}
else
{
echo 'Could not write to file<br />';
}
Edit: Or even better:
if(fwrite($fh, $prod_str) !== false)
{
echo 'Done!<br />';
}
else
{
echo 'Could not write to file<br />';
}
Upvotes: 2