PHP convert XML to JSON

前端 未结 20 1406
生来不讨喜
生来不讨喜 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("");
    
    // 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);
            }
        }
    }
    

提交回复
热议问题