我编写了一个脚本,将XML文件打印到屏幕上,但我希望它打开一个下载对话框,以便我可以将其保存为文件。
我怎么能这样做?
日Thnx!
脚本:
<?php
print '<?xml version="1.0" encoding="UTF-8" ?>';
print "\n <data>";
...
print "\n </data>";
?>
答案 0 :(得分:4)
尝试设置标题:
<?php
header('Content-Type: text/xml');
header('Content-Disposition: attachment; filename="example.xml"');
header('Content-Transfer-Encoding: binary');
print '<?xml version="1.0" encoding="UTF-8" ?>';
print "\n <data>";
...
print "\n </data>";
?>
答案 1 :(得分:3)
尝试使用以下命令强制浏览器显示“另存为...”对话框: 浏览器显示内容类型的“另存为...”对话框,它不知道如何解释/显示,或者在标题中指示它。只需知道正确的标题,您就可以指定下载它,默认文件名,内容类型以及如何缓存它。
<?php
$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
$xml .= "\n <data>";
// Create the rest of your XML Data...
$xml .= "\n </data>";
downloader($xml, 'yourFile.xml', 'application/xml');
功能代码:
<?php
if(!function_exists('downloader'))
{
function downloader($data, $filename = true, $content = 'application/x-octet-stream')
{
// If headers have already been sent, there is no point for this function.
if(headers_sent()) return false;
// If $filename is set to true (or left as default), treat $data as a filepath.
if($filename === true)
{
if(!file_exists($data)) return false;
$data = file_get_contents($data);
}
if(strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== false)
{
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header('Content-Type: '.$content);
header('Pragma: public');
header('Content-Length: '.strlen($data));
}
else
{
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Type: '.$content);
header('Expires: 0');
header('Pragma: no-cache');
header('Content-Length: '.strlen($data));
}
// Send file to browser, and terminate script to prevent corruption of data.
exit($data);
}
}