PHP以漂亮格式打印xml文件

问题描述 投票:1回答:2

我需要通过Apache请求在浏览器中显示一个XML文件。因此,我可以将文件提供给freeswitch。我的PHP代码是这样的:

<?php
header('Content-Type: text/xml');
$xml=simplexml_load_file("test.xml") or die("not found");
echo "<pre>".print_r($xml,true)."</pre>";
?>

但是我得到这个输出:

<pre>SimpleXMLElement Object
(
[@attributes] => Array
    (
        [type] => freeswitch/xml
    )

[section] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [name] => configuration
            )

        [configuration] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [description] => Network Lists
                        [name] => acl.conf
                    )

                [network-lists] => SimpleXMLElement Object
                    (
                        [list] => Array
                            (
                                [0] => SimpleXMLElement Object
                                    (
                                        [@attributes] => Array
                                            (
                                                [name] => localhost_allow
                                                [default] => allow
                                            )

                                        [node] => SimpleXMLElement Object
                                            (
                                                [@attributes] => Array
                                                    (
                                                        [type] => allow
                                                        [cidr] => 127.0.0.1/32
                                                    )
)
</pre>

我只需要在浏览器中输出漂亮的xml。或者,我可以通过其他方式提供xml文件。任何想法?谢谢

php xml pretty-print
2个回答
4
投票

您无需将XML文件作为对象加载。只需加载文件的原始内容并打印:

$file = file_get_contents("test.xml");
echo $file;

浏览器将为您完成剩下的工作。


2
投票

也许这可以解决问题,如果没有,我相信您必须解析xml,然后可以根据需要对其进行格式化。

 <?php
    header('Content-Type: text/xml');
    $xml=simplexml_load_file("test.xml") or die("not found");
    echo $xml->asXML();
 ?>
© www.soinside.com 2019 - 2024. All rights reserved.