Replace 1st fgets with this code, to be sure fgets understand line termination correctly:
$fgets = '';while (is_resource($stream) && !feof($stream)) { $fgets .= fgets($stream); }