带有 utf-8 的 xml 的 PHP 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5212435/
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 20:39:00  来源:igfitidea点击:

PHP header for xml with utf-8

phpxmldomcharacter-encodingheader

提问by msmafra

I'm using the header()function to turn a file into XML standard. The problem is when I use <?php header("Content-type: text/xml; charset=utf-8"); ?> it just renders the <?xml version="1.0"?>, without the enconding/charset. Am I using it wrongly?

我正在使用header()函数将文件转换为 XML 标准。问题是当我使用<?php header("Content-type: text/xml; charset=utf-8"); ?> 它只是呈现<?xml version="1.0"?>, 没有编码/字符集。我用错了吗?

采纳答案by John Flatness

The header()function just modifies HTTP headers. The code you posted sets a Content-Typeheader, which is important for telling browsers and other clients what type of file you're serving.

header()函数只是修改 HTTP 标头。您发布的代码设置了一个Content-Type标头,这对于告诉浏览器和其他客户端您所提供的文件类型很重要。

The <?xml version="1.0"?>line you're talking about is part of the document itself, and not affected by the HTTP headers.

<?xml version="1.0"?>您正在谈论的行是文档本身的一部分,不受 HTTP 标头的影响。

Your tags say you're using DOM to create your XML document. If you change your DomDocument constructor to also pass the charset,

您的标签表明您正在使用 DOM 来创建您的 XML 文档。如果您更改 DomDocument 构造函数以同时传递字符集,

$doc = new DomDocument('1.0', 'UTF-8');

It should output that charset in the XML document.

它应该在 XML 文档中输出该字符集。

回答by Michael Madsen

headerjust sets a HTTP header in the result. PHP doesn't do anything else with the value, so it's up to you to make sure it's being used properly.

header只需在结果中设置一个 HTTP 标头。PHP 不会对该值执行任何其他操作,因此由您来确保它被正确使用。

If you're using an XML library to generate your XML (including the prologue), check the documentation for that library. If you're outputting the XML "by hand" (o, you need to add the necessary attribute to the prologue yourself.

如果您使用 XML 库生成 XML(包括序言),请查看该库的文档。如果您“手动”输出 XML(o,您需要自己将必要的属性添加到序言中。

回答by Sahan

You can also use

你也可以使用

<?php echo '<?xml version"1.0" encoding="UTF-8"?>'; ?>