【问题标题】:How to output XML string from PHP如何从 PHP 输出 XML 字符串
【发布时间】:2011-04-19 13:42:00
【问题描述】:

我正在获取一个 XML 字符串并在 PHP 中对其进行编辑,以便在访问 PHP 文件时最终输出编辑后的 ​​XML 字符串。我一直在尝试使用 echo 和 print 来输出 XML 文档,但它只打印最里面的标签内的数据。我希望它能够像您直接加载 XML 文档(例如 test.com/example.xml)一样运行。相反,它只打印出字符串的一部分而不是整个字符串。打印语句如下。有什么建议吗?

打印 <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">

<Document> <Style id="undecorated_style"> &lt;BalloonStyle&gt; &lt;displayMode&gt;undecorated&lt;/displayMode&gt; &lt;/BalloonStyle&gt; &lt;/Style&gt;

<Placemark>
    <name>Relative Marker Example</name>
    <description><![CDATA[
    <div style="position: absolute; width: 100px; height: 100px; left: -50px; top: -50px"><img width="100px" height="100px" src="http://argonapps.gatech.edu/examples/FrameMarkerThin_005.png"/></div>
    ]]>
    </description>
    <balloonVisibility>1</balloonVisibility>
    <Marker>
        <markerType>framesimpleid</markerType>
        <markerId>-1</markerId> <!-- integer value (-1 means follow any marker of markerType) -->
        <locationMode>relative</locationMode> <!-- default (ignore), relative (update location), fixed (update camera) -->
        <orientationMode>fixed</orientationMode>
        <scale>
            <x>0.076</x> <!-- test marker is 0.038 meters -->
            <y>0.076</y>
            <z>0.076</z>
        </scale>
    </Marker>
    <styleUrl>#undecorated_style</styleUrl>
</Placemark>

';

在浏览器中打开文件只显示:

相对标记示例 ]]> 1 帧simpleid -1 相对固定 0.076 0.076 0.076 #undecorated_style

而不是简单的 xml。

【问题讨论】:

    标签: php xml


    【解决方案1】:

    在打印之前,添加内容类型标题。

    要么

    header('Content-type: text/xml');
    

    或者更适合 KML

    header('Content-type: application/vnd.google-earth.kml+xml');
    

    如果您想在浏览器中将其作为源代码查看,请阅读:http://www.w3schools.com/xml/xml_view.asp

    你也可以强制它显示为文本,通过添加

     header('Content-type: text/plain');
    

    【讨论】:

    • 感谢您的回复。浏览器现在只显示: undecorated Relative Marker Example 1 framessimpleid -1 relative fixed 0.076 0.076 0.076 #undecorated_style
    • 哇!太感谢了。您提供的第二个标题有效。
    【解决方案2】:

    这可能是因为您的浏览器正在尝试呈现 XML(类似于它加载 HTML 的方式,您只看到内容而不是标签)。

    如果您在浏览器中执行“查看源代码”,您应该会看到原始 XML。

    您可以随时将标签更改为 <和>以便将其显示为文本

    print htmlentities('<Placemark>.....</Placemark>');
    

    【讨论】:

      【解决方案3】:

      echo输出您的输出之前,您应该首先发送正确的 XML 数据标头:

      header("Content-type: text/xml");
      // Or
      header("Content-type: application/xml");
      

      编辑:请注意,您的浏览器可能仍只会呈现内部文本。查看页面源以查看您的 XML。

      【讨论】:

      • @vartec tools.ietf.org/html/rfc3023#section-3.2 虽然我自己会使用text/xml,但我认为application/xml 也可以。
      • 这就是我删除评论的原因。虽然在实践中没有看到application/xml
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 2015-05-28
      • 1970-01-01
      相关资源
      最近更新 更多