How to convert array to SimpleXML

前端 未结 30 3042
遇见更好的自我
遇见更好的自我 2020-11-21 06:52

How can I convert an array to a SimpleXML object in PHP?

30条回答
  •  星月不相逢
    2020-11-21 07:15

    Just a edit on a function above, when a key is numeric, add a prefix "key_"

    // initializing or creating array
    $student_info = array(your array data);
    
    // creating object of SimpleXMLElement
    $xml_student_info = new SimpleXMLElement("");
    
    // function call to convert array to xml
    array_to_xml($student,$xml_student_info);
    
    //saving generated xml file
    $xml_student_info->asXML('file path and name');
    
    
    function array_to_xml($student_info, &$xml_student_info) {
         foreach($student_info as $key => $value) {
              if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml_student_info->addChild("$key");
                    array_to_xml($value, $subnode);
                }
                else{
                    $subnode = $xml_student_info->addChild("key_$key");
                    array_to_xml($value, $subnode);
                }
              }
              else {
                   if(!is_numeric($key)){
                        $xml_student_info->addChild("$key","$value");
                   }else{
                        $xml_student_info->addChild("key_$key","$value");
                   }
              }
         }
    }
    

提交回复
热议问题