PHP file_get_contents() 和 XML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16544960/
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
PHP file_get_contents() and XML files
提问by Marek Haj?man
in PHP I want to load a XML file (as a text file) and show its content (as a text) on a screen. I have a simple XML in the form
在 PHP 中,我想加载一个 XML 文件(作为文本文件)并在屏幕上显示其内容(作为文本)。我有一个简单的 XML 形式
<root> <parent>Parent text. </parent></root>
If I use
如果我使用
$myxmlfilecontent = file_get_contents('./myfile.xml');
echo $myfilecontent;
prints only the content of the node "parent", it prints only "Parent text.", not the whole file content.
只打印节点“父”的内容,它只打印“父文本”,而不是整个文件内容。
回答by Ph.T
When you print XML in an HTML page, the XML is assimilated to HTML, so you do not see the tags.
当您在 HTML 页面中打印 XML 时,XML 被同化为 HTML,因此您看不到标签。
To see the tags as text, you should replace them with the HTML corresponding entity:
要将标签视为文本,您应该将它们替换为 HTML 对应的实体:
$myxmlfilecontent = file_get_contents('./myfile.xml');
echo str_replace('<', '<', $myxmlfilecontent);
that should do the trick
这应该够了吧
I recommend you to also enclose the xml into a 'pre' to preserve spaces for presentation
我建议您还将 xml 包含在“pre”中以保留用于演示的空间
$myxmlfilecontent = file_get_contents('./myfile.xml');
echo '<pre>' . str_replace('<', '<', $myxmlfilecontent) . '</pre>';
回答by Naftali aka Neal
It isprinting the whole thing (if you look at the source of the page).
它正在打印整个内容(如果您查看页面的来源)。
But if the file type is set as HTML, then you will not see the nodes.
但如果文件类型设置为 HTML,则您将看不到节点。
回答by hakre
You need to tell your browser that the content you send to it (you "echo" it to the browser) is XML. This is done by sending the proper Content-Type header:
您需要告诉浏览器您发送给它的内容(您将其“回显”给浏览器)是 XML。这是通过发送正确的 Content-Type 标头来完成的:
header('Content-Type: text/xml');
$myxmlfilecontent = file_get_contents('./myfile.xml');
echo $myxmlfilecontent;
You browser will then try to display the XML as best as possible, normally with syntax-highlighting and controls to open and collapse nodes.
然后,您的浏览器将尝试尽可能最好地显示 XML,通常使用语法突出显示和用于打开和折叠节点的控件。
Otherwise, by default your browser will try to display the text as HTML and because all those tags are not valid HTML tags, they are hidden. That is the default behavior of a browser.
否则,默认情况下,您的浏览器将尝试将文本显示为 HTML,并且由于所有这些标签都不是有效的 HTML 标签,因此它们将被隐藏。这是浏览器的默认行为。
回答by rkosegi
Add following snipet before any output:
在任何输出之前添加以下代码片段:
header("Content-Type: text/plain");
This will force user agent (browser) to treat your output as plain text.
这将强制用户代理(浏览器)将您的输出视为纯文本。
On other hand, you can use some syntax highlighter like discussed here : PHP code to syntax-format XML content in a `pre` tag
另一方面,您可以使用这里讨论的一些语法高亮显示:PHP 代码在 `pre` 标签中对 XML 内容进行语法格式化