3

我编写了一个脚本,将 XML 文件打印到屏幕上,但我希望它打开一个下载对话框,以便我可以将其保存为文件。

我怎么能这样做?

谢谢!

剧本:

<?php
print '<?xml version="1.0" encoding="UTF-8" ?>';
print "\n <data>";
...
print "\n </data>";
?>
4

2 回答 2

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>";
?>
于 2009-09-08T12:04:27.360 回答
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);
   }
 }
于 2009-09-08T12:06:07.683 回答