使用 php 输出原始 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7139708/
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
Output raw XML using php
提问by RNs_Ghost
I want to output raw xml in a manner similar to http://www.google.com/ig/api?weather=Mountain+Viewbut using PHP.
我想以类似于http://www.google.com/ig/api?weather=Mountain+View但使用 PHP的方式输出原始 xml 。
I have a very simple php script on my webserver:
我的网络服务器上有一个非常简单的 php 脚本:
<?php
$output = "<root><name>sample_name</name></root>";
print ($output);
?>
All I can see in Chrome/firefox is "sample_name". I want to see:
我在 Chrome/firefox 中只能看到“sample_name”。我想看看:
<root>
<name>sample_name</name>
</root>
I cannot find a tutorial for anything THIS simple.
我找不到任何这么简单的教程。
Thanks
谢谢
回答by Arnaud Le Blanc
By default PHP sets the Content-Type to text/html, so the browsers are displaying your XML document as an HTML page.
默认情况下,PHP 将 Content-Type 设置为 text/html,因此浏览器将您的 XML 文档显示为 HTML 页面。
For the browser to treat the document as XML you have to set the content-type:
为了让浏览器将文档视为 XML,您必须设置内容类型:
header('Content-Type: text/xml');
Do this before printing anything in your script.
在您的脚本中打印任何内容之前执行此操作。
回答by CONvid19
<?php
header('Content-Type: application/xml');
$output = "<root><name>sample_name</name></root>";
print ($output);
?>
回答by Lukas Knuth
You only see "sample_name" because you didn't specify that your output is XML and the browser thinks it's HTML so your XML-Elements are interpreted as HTML-Elements.
您只看到“sample_name”,因为您没有指定您的输出是 XML 并且浏览器认为它是 HTML,因此您的 XML-Elements 被解释为 HTML-Elements。
To see the raw XML, you need to tell the browser that you're actually sending XML by sending the correct content-type in the HTTP header:
要查看原始 XML,您需要通过在 HTTP 标头中发送正确的内容类型来告诉浏览器您实际上正在发送 XML:
header('Content-Type: application/xml');
This needs to be send (put in the code) before you put out anything else.
这需要在您发布其他任何内容之前发送(放入代码中)。
回答by IMSoP
For completeness sake, as nobody's mentioned it yet, you can also output raw XML withinan HTML page, by escaping <
as <
, >
as >
, and &
as &
. To do that, use the awkwardly named htmlspecialchars
function.
为了完整起见,正如还没有人提到的那样,您还可以通过转义as 、as和as 来在HTML 页面中输出原始 XML 。为此,请使用命名笨拙的函数。<
<
>
>
&
&
htmlspecialchars
Often, you'll also want to preserve whitespace in the argument, which can be done by surrounding it in <pre>
tags. So a common line for debugging or including a sample is this:
通常,您还希望在参数中保留空格,这可以通过将其括在<pre>
标签中来完成。因此,调试或包含示例的常用行是:
echo '<pre>' . htmlspecialchars($raw_xml) . '</pre>';
回答by user110357
Just press Ctrl+U(Control+U), Your browser will display the page's raw source code under a new Tab, be it XML or HTML or whatever else...
只需按Ctrl+ U(Control+U),您的浏览器将在新选项卡下显示页面的原始源代码,无论是 XML 或 HTML 还是其他任何...