what happens if you remove the header directives? You must know that headers are by definition concluded by a new line. I could imagine that this is a \n vs \r\n conflict.
If everything fails, get the whole output into buffer and trim it later:
ob_start();
...your code...
$out = ob_get_contents();
ob_end_clean();
echo trim($out);
Best regards
Zsolt