如何在 PHP 中以 HTML 显示 XML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2864303/
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
How to display XML in HTML in PHP?
提问by Tomasz Smykowski
I have a string with XML:
我有一个带有 XML 的字符串:
$string =
"
<shoes>
<shoe>
<shouename>Shoue</shouename>
</shoe>
</shoes>
";
And would like display it on my website like this:
并希望像这样在我的网站上显示它:
This is XML string content:
<shoes>
<shoe>
<shouename>Shoue</shouename>
</shoe>
</shoes>
So I would like to do it:
所以我想这样做:
- on site, not in textbox
- without external libraries, frameworks etc.
- formatted with proper new lines
- formatted with tabs
- without colors etc., only text
- 在网站上,而不是在文本框中
- 没有外部库、框架等。
- 用适当的新行格式化
- 用制表符格式化
- 没有颜色等,只有文字
So how to do it in plain and simple way?
那么如何以简单明了的方式做到这一点呢?
回答by Chris
If you just want a plain-text representation of your (pre-formatted) string, you can wrap it in HTML <pre/>tags and use htmlentitiesto escape the angle brackets:
如果您只想要(预格式化的)字符串的纯文本表示,您可以将其包装在 HTML<pre/>标签中并用于htmlentities转义尖括号:
<?PHP echo '<pre>', htmlentities($string), '</pre>'; ?>
回答by Sinan
you can use htmlentities(), htmlspecialchars()or some similar function.
您可以使用htmlentities(),htmlspecialchars()或一些类似的功能。
回答by justastefan
It should work like that:
它应该像这样工作:
echo '<p>This is XML string content:</p>'
echo '<pre>';
echo htmlspecialchars($string);
echo '</pre>';
回答by Frank Forte
If it is a SimpleXMLobject
如果是 SimpleXMLobject
<pre>
<?php
echo htmlspecialchars(print_r($obj,true));
?>
</pre>
回答by H.Tries
I searched for a solution to have slightly coloured output:
我搜索了一个解决方案来输出略带颜色的输出:
$escaped = htmlentities($content);
$formatted = str_replace('<', '<span style="color:blue"><', $escaped);
$formatted = str_replace('>', '></span>', $formatted);
echo "<pre>$formatted</pre>\n";

