我正在尝试用 php 写入文件并下载它。总是第一行出现空白,这是错误的
I am trying write file with php and download it. Always first line appears in blank and that is wrong
我正在生成一个类似于 xml 的文件。
当我拥有所有字符串时,我会尝试即时编写和下载它。
当我打开文件时问题就开始了:第一行是空白,纯文本从第二行开始。我已经用 fwrite、fput 和 file_put_contents() 进行了测试……但是……
我一直没能解决问题...
这是一段代码:
function dw($str, $name){
$handle = fopen($name.'.fmt', "w");
fwrite($handle, utf8_encode($str));
fclose($handle);
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename='.basename($name.'.fmt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name.'.fmt'));
readfile($name.'.fmt');
exit;
}
我找到了解决方案(也许有人需要这个答案):
$handle = fopen($name.'.fmt', "wb");
rewind($handle);
fwrite($handle, $new_dom->saveXML());
fclose($handle);
header('Content-Description: File Transfer');
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename=' . basename($name.'.fmt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name.'.fmt'));
ob_clean();
readfile($name.'.fmt');
我正在生成一个类似于 xml 的文件。
当我拥有所有字符串时,我会尝试即时编写和下载它。
当我打开文件时问题就开始了:第一行是空白,纯文本从第二行开始。我已经用 fwrite、fput 和 file_put_contents() 进行了测试……但是……
我一直没能解决问题...
这是一段代码:
function dw($str, $name){
$handle = fopen($name.'.fmt', "w");
fwrite($handle, utf8_encode($str));
fclose($handle);
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename='.basename($name.'.fmt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name.'.fmt'));
readfile($name.'.fmt');
exit;
}
我找到了解决方案(也许有人需要这个答案):
$handle = fopen($name.'.fmt', "wb");
rewind($handle);
fwrite($handle, $new_dom->saveXML());
fclose($handle);
header('Content-Description: File Transfer');
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename=' . basename($name.'.fmt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($name.'.fmt'));
ob_clean();
readfile($name.'.fmt');