php 让用户下载 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4349202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:45:58  来源:igfitidea点击:

Let user download a XML file

phpheader

提问by PeeHaa

I have prepared an XML string in PHP and I would like to let the user download the string in an XML file.

我在 PHP 中准备了一个 XML 字符串,我想让用户下载 XML 文件中的字符串。

Is it possible to offer the user the download (e.g. text.xml) without physically saving the xml file to the server?

是否可以在不将 xml 文件物理保存到服务器的情况下向用户提供下载(例如 text.xml)?

回答by Ish

<?php
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="text.xml"');

echo $xml_contents;

回答by Vlado

If you use some kind of output buffering as a part of your framework you must add exit() below the XML output, like that:

如果您使用某种输出缓冲作为框架的一部分,则必须在 XML 输出下方添加 exit() ,如下所示:

<?php
header('Content-type: text/xml');
header('Content-Disposition: attachment; filename="text.xml"');

echo $xml_contents;
exit();

Otherwise you'll get the whole buffered page, not only the XML output.

否则,您将获得整个缓冲页面,而不仅仅是 XML 输出。

回答by nukeurself

When you create the XML file first using for example php′s SimpleXMLElement you might want to clean up first to prevent that html code is in that downloaded xml file. Here is what i came up with:

当您首先使用例如 php 的 SimpleXMLElement 创建 XML 文件时,您可能需要先清理以防止 html 代码位于该下载的 xml 文件中。这是我想出的:

 $xml = new SimpleXMLElement("<root/>");
 $xml->addChild("foo", "bar");

 ob_end_clean();
 header_remove();

 header("Content-type: text/xml");
 header('Content-Desposition: attachment; filename="foobar.xml"');
 echo $xml->asXML();
 exit();

This is how the downloaded "foobar.xml" file looks then:

这是下载的“foobar.xml”文件的样子:

<?xml version="1.0"?>
<root><foo>bar</foo></root>

Testet with Chrome Version 65.0.3325.181, Firefox 59.0.1 and Microsoft Edge 41.16299.371.0

使用 Chrome 版本 65.0.3325.181、Firefox 59.0.1 和 Microsoft Edge 41.16299.371.0 进行测试