如何从XML字符串获取JSON

编程入门 行业动态 更新时间:2024-10-27 02:31:02
本文介绍了如何从XML字符串获取JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的XML字符串:

This is my XML string:

<root>EXTRA <elem id="123" at="abc">HelloText</elem> </root>

如何将其转换为JSON格式(带有属性和HelloText)?

How can I convert it to a JSON format (WITH attributes and HelloText) ?

推荐答案

因为RJS不想检查我向他建议的答案,所以它来自这篇文章:

Because RJS doesn't want to check the answer i suggested to him, here is it from this post:

一个常见的陷阱是忘记json_encode()不尊重具有textvalue和attribute的元素.它将选择其中之一,即数据丢失.下面的功能解决了这个问题.如果决定使用json_encode/decode方式,建议使用以下功能.

A common pitfall is to forget that json_encode() does not respect elements with a textvalue and attribute(s). It will choose one of those, meaning dataloss. The function below solves that problem. If one decides to go for the json_encode/decode way, the following function is advised.

function json_prepare_xml( $domNode ){ foreach( $domNode->childNodes as $node) if($node->hasChildNodes()) json_prepare_xml($node); if( $domNode->hasAttributes() && strlen($domNode->nodeValue) ){ $domNode->setAttribute("nodeValue", $node->textContent ); $node->nodeValue = ""; } return $node; } $dom->loadXML( file_get_contents($xmlfile) ); json_prepare_xml($dom); $sxml = simplexml_load_string( $dom->saveXML() ); $json = json_decode( json_encode( $sxml ) ) );

这样做,<foo bar="3">Lorem</foo>在您的JSON中将不会以{"foo":"Lorem"}结尾.

by doing so, <foo bar="3">Lorem</foo> will not end up as {"foo":"Lorem"} in your JSON.

更多推荐

如何从XML字符串获取JSON

本文发布于:2023-10-12 00:01:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483216.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   XML   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!