PHP convert XML to JSON

前端 未结 20 1458
生来不讨喜
生来不讨喜 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:21
    $templateData =  $_POST['data'];
    
    // initializing or creating array
    $template_info =  $templateData;
    
    // creating object of SimpleXMLElement
    $xml_template_info = new SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");
    
    // function call to convert array to xml
    array_to_xml($template_info,$xml_template_info);
    
    //saving generated xml file
     $xml_template_info->asXML(dirname(__FILE__)."/manifest.xml") ;
    
    // function defination to convert array to xml
    function array_to_xml($template_info, &$xml_template_info) {
        foreach($template_info as $key => $value) {
            if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml_template_info->addChild($key);
                    if(is_array($value)){
                        $cont = 0;
                        foreach(array_keys($value) as $k){
                            if(is_numeric($k)) $cont++;
                        }
                    }
    
                    if($cont>0){
                        for($i=0; $i < $cont; $i++){
                            $subnode = $xml_body_info->addChild($key);
                            array_to_xml($value[$i], $subnode);
                        }
                    }else{
                        $subnode = $xml_body_info->addChild($key);
                        array_to_xml($value, $subnode);
                    }
                }
                else{
                    array_to_xml($value, $xml_template_info);
                }
            }
            else {
                $xml_template_info->addChild($key,$value);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 07:22

    Best solution which works like a charm

    $fileContents= file_get_contents($url);
    
    $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
    
    $fileContents = trim(str_replace('"', "'", $fileContents));
    
    $simpleXml = simplexml_load_string($fileContents);
    
    //$json = json_encode($simpleXml); // Remove // if you want to store the result in $json variable
    
    echo '<pre>'.json_encode($simpleXml,JSON_PRETTY_PRINT).'</pre>';
    

    Source

    0 讨论(0)
提交回复
热议问题