php - 当有 CDATA 时,将 xml 转换为 json 不起作用 [英] php - converting xml to json does not work when there is CDATA

查看:35
本文介绍了php - 当有 CDATA 时,将 xml 转换为 json 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用以下 php 代码将 xml 转换为 json:

If I use the following php code to convert an xml to json:

<?php

header("Content-Type:text/json");

$resultXML = "
<QUERY>
   <Company>fcsf</Company>
   <Details>
      fgrtgrthtyfgvb
   </Details>
</QUERY>
";

$sxml = simplexml_load_string($resultXML);
echo  json_encode($sxml);
?>

我明白了

{"Company":"fcsf","Details":"\n      fgrtgrthtyfgvb\n   "}

但是,如果我在 Details 元素中使用 CDATA 如下:

However, If I use CDATA in the Details element as follows:

<?php

header("Content-Type:text/json");

$resultXML = "
<QUERY>
   <Company>fcsf</Company>
   <Details><![CDATA[
      fgrtgrthtyfgvb]]>
   </Details>
</QUERY>
";

$sxml = simplexml_load_string($resultXML);
echo  json_encode($sxml);

?>

我得到以下

{"Company":"fcsf","Details":{}}

在这种情况下,Details 元素为空.知道为什么 Details 是空白的以及如何更正吗?

In this case the Details element is blank. Any idea why Details is blank and how to correct this?

推荐答案

不是 JSON 编码的问题 – var_dump($sxml->Details)向您展示 SimpleXML 之前已经把它搞砸了,因为您只会得到

This is not a problem with the JSON encoding – var_dump($sxml->Details) shows you that SimpleXML already messed it up before, as you will only get

object(SimpleXMLElement)#2 (0) {
}

——一个空"的 SimpleXMLElement,CDATA 内容已经在那里丢失了.

– an "empty" SimpleXMLElement, the CDATA content is already missing there.

我们弄清楚这一点后,通过谷歌搜索simplexml cdata"将我们直接带到SimpleXML 函数手册页上的第一个用户评论,有解决方案:

And after we figured that out, googling for "simplexml cdata" leads us straight to the first user comment on the manual page on SimpleXML Functions, that has the solution:

如果您在访问 simplexml 文档中的 CDATA 时遇到问题,则无需在使用 simplexml 加载 CDATA 之前 str_replace/preg_replace CDATA.

If you are having trouble accessing CDATA in your simplexml document, you don't need to str_replace/preg_replace the CDATA out before loading it with simplexml.

您可以改为这样做,您的所有 CDATA 内容将作为字符串合并到元素内容中.

You can do this instead, and all your CDATA contents will be merged into the element contents as strings.

$xml = simplexml_load_file($xmlfile, 'SimpleXMLElement', LIBXML_NOCDATA);

所以,使用

$sxml = simplexml_load_string($resultXML, 'SimpleXMLElement', LIBXML_NOCDATA);

在你的代码中,你会得到

in your code, and you’ll get

{"Company":"fcsf","Details":"\n      fgrtgrthtyfgvb\n   "}

在 JSON 编码之后.

after JSON-encoding it.

这篇关于php - 当有 CDATA 时,将 xml 转换为 json 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆