Ooops...my bad. I thought you want to append content rather than replace it.
In this case 'w' is correct option for fopen to be used. Maybe w+, but in any way, as I have read your code more deeply, the fopen function may not be the issue...
However, if I am not mistaking, ob_end_clean clears the buffer without output, while ob_get_flush output the buffer as a string. The difference seems to be that end clean simply empties the buffer with no output, while get_flush outputs a string and closes buffering.