PHP convert XML to JSON

前端 未结 20 1463
生来不讨喜
生来不讨喜 2020-11-22 06:25

I am trying to convert xml to json in php. If I do a simple convert using simple xml and json_encode none of the attributes in the xml show.

$xml = simplexml         


        
20条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:59

    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);
        } else {
          if($domNode->hasAttributes() && strlen($domNode->nodeValue)){
             $domNode->setAttribute("nodeValue", $node->textContent);
             $node->nodeValue = "";
          }
        }
      }
    }
    
    $dom = new DOMDocument();
    $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, Lorem will not end up as {"foo":"Lorem"} in your JSON.

提交回复
热议问题