PHP file_get_contents() and XML files [dup

2019-07-18 04:20发布

This question already has an answer here:

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

<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.

4条回答
劫难
2楼-- · 2019-07-18 04:20

When you print XML in an HTML page, the XML is assimilated to HTML, so you do not see the tags.

To see the tags as text, you should replace them with the HTML corresponding entity:

$myxmlfilecontent = file_get_contents('./myfile.xml');
echo str_replace('<', '&lt;', $myxmlfilecontent);

that should do the trick

I recommend you to also enclose the xml into a 'pre' to preserve spaces for presentation

$myxmlfilecontent = file_get_contents('./myfile.xml');
echo '<pre>' . str_replace('<', '&lt;', $myxmlfilecontent) . '</pre>';
查看更多
劳资没心,怎么记你
3楼-- · 2019-07-18 04:27

It is printing 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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-18 04:29

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:

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.

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.

查看更多
手持菜刀,她持情操
5楼-- · 2019-07-18 04:38

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

查看更多
登录 后发表回答