PHP convert XML to JSON

前端 未结 20 1498
生来不讨喜
生来不讨喜 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条回答
  •  失恋的感觉
    2020-11-22 07:20

    After researching a little bit all of the answers, I came up with a solution that worked just fine with my JavaScript functions across browsers (Including consoles / Dev Tools) :

     childNodes as $node) {
       if ( $node -> hasChildNodes() ) { json2xml( $node ); }
       else {
        if ( $domNode -> hasAttributes() && strlen( $domNode -> nodeValue ) ) {
         $domNode -> setAttribute( "nodeValue", $node -> textContent );
         $node -> nodeValue = "";
        }
       }
      }
     }
    
     function jsonOut( $file ) {
      $dom = new DOMDocument();
      $dom -> loadXML( file_get_contents( $file ) );
      json2xml( $dom );
      header( 'Content-Type: application/json' );
      return str_replace( "@", "", json_encode( simplexml_load_string( $dom -> saveXML() ), JSON_PRETTY_PRINT ) );
     }
    
     $output = jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' );
    
     echo( $output );
    
     /*
      Or simply 
      echo( jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' ) );
     */
    
    ?>
    

    It basically creates a new DOMDocument, loads and XML file into it and traverses through each one of the nodes and children getting the data / parameters and exporting it into JSON without the annoying "@" signs.

    Link to the XML file.

提交回复
热议问题