Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

php - how to get JSON from XML string

This is my XML string:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...