PHP XML导出为文件下载

PHP XML导出为文件下载,php,drupal,drupal-views,Php,Drupal,Drupal Views,我编写了一个脚本,将XML文件打印到屏幕上,但我希望它打开一个下载对话框,以便将其保存为文件 我怎么能这么做 thnx 剧本: <?php print '<?xml version="1.0" encoding="UTF-8" ?>'; print "\n <data>"; ... print "\n </data>"; ?> 尝试将标题设置为正确: <?php header('Content-Type: text/xml'); heade

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

我怎么能这么做

thnx

剧本:

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

尝试将标题设置为正确:

<?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>";
?>

尝试使用以下命令强制浏览器显示“另存为…”对话框: 浏览器会显示一个“另存为…”对话框,用于它不知道如何解释/显示的内容类型,或者当它在标题中被指示时。只需知道正确的头文件,就可以指定下载头文件、默认文件名、内容类型以及缓存方式

<?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');

肯定不能回答您的问题,但我建议使用一些库/类来生成xml,而不是“手动”构造它(例如SimpleXML-在Drupal代码中经常使用,如果您有更复杂的需求,也可以使用DOMDocument)。这节省了大量的工作。@headkit:如果您已经为此编写了一个模块。请给我代码。如果您回复,我将通过邮件提供id。感谢没有创建模块,很抱歉。您可以再次尝试此操作,放置
ob_end_clean()在头声明前面调用。根据您的标记,我假设这发生在Drupal上下文中,Drupal可能会通过预先设置一些头来进行干预。清除输出缓冲区可能会有所不同。是否收到标头已发送的任何警告?查看您的apache登录/var/log/apache2/左右。那样的话,你可以试试亨里克的建议。
<?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);
   }
 }