PHP file_get_contents()和XML文件

Mar*_*man 3 php xml file-get-contents

在PHP中我想加载一个XML文件(作为文本文件)并在屏幕上显示其内容(作为文本).我在表单中有一个简单的XML

<root> <parent>Parent text. </parent></root>
Run Code Online (Sandbox Code Playgroud)

如果我使用

$myxmlfilecontent = file_get_contents('./myfile.xml');
echo $myfilecontent; 
Run Code Online (Sandbox Code Playgroud)

仅打印节点"父"的内容,它只打印"父文本",而不是整个文件内容.

Ph.*_*h.T 6

当您在HTML页面中打印XML时,XML被同化为HTML,因此您看不到标记.

要将标记视为文本,您应该将它们替换为HTML对应的实体:

$myxmlfilecontent = file_get_contents('./myfile.xml');
echo str_replace('<', '&lt;', $myxmlfilecontent);
Run Code Online (Sandbox Code Playgroud)

这应该够了吧

我建议你也将xml封装到'pre'中以保留用于演示的空间

$myxmlfilecontent = file_get_contents('./myfile.xml');
echo '<pre>' . str_replace('<', '&lt;', $myxmlfilecontent) . '</pre>';
Run Code Online (Sandbox Code Playgroud)


Nea*_*eal 3

正在打印整个内容(如果您查看页面的来源)。

但如果文件类型设置为 HTML,那么您将看不到节点。