gpt4 book ai didi

php - 当有 CDATA 时,将 xml 转换为 json 不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:52:04 27 4
gpt4 key购买 nike

如果我使用以下 php 代码将 xml 转换为 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,如下所示:

<?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 是空白的吗?如何更正它?

最佳答案

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

object(SimpleXMLElement)#2 (0) {
}

– 一个“空的”SimpleXMLElement,那里已经缺少 CDATA 内容。

我们弄明白之后,谷歌搜索“simplexml cdata”直接将我们带到了the first user comment on the manual page on SimpleXML Functions。 ,有解:

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.

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);

在你的代码中,你会得到

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

在对其进行 JSON 编码之后。

关于php - 当有 CDATA 时,将 xml 转换为 json 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21548443/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com