-5

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

RJS
  • 13
  • 3
  • @RJS The downvotes are probably because this is an off-topic question. See [help/on-topic] point #4 –  Dec 24 '14 at 08:45
  • http://stackoverflow.com/questions/8830599/php-convert-xml-to-json – geekido Dec 24 '14 at 09:05
  • @RJS, did you spot the Coder Of Salvation's answer from here? http://stackoverflow.com/questions/8830599/php-convert-xml-to-json I think it is right for your situation. – bksi Dec 24 '14 at 10:21

1 Answers1

0

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.

Community
  • 1
  • 1
bksi
  • 1,606
  • 1
  • 23
  • 45