How to convert array to SimpleXML

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

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

30条回答
  •  天涯浪人
    2020-11-21 07:22

    I wanted a code that will take all the elements inside an array and treat them as attributes, and all arrays as sub elements.

    So for something like

    array (
    'row1' => array ('head_element' =>array("prop1"=>"some value","prop2"=>array("empty"))),
    "row2"=> array ("stack"=>"overflow","overflow"=>"overflow")
    );
    

    I would get something like this

    
    
      
        
          
        
      
      
     
    

    To achive this the code is below, but be very careful, it is recursive and may actually cause a stackoverflow :)

    function addElements(&$xml,$array)
    {
    $params=array();
    foreach($array as $k=>$v)
    {
        if(is_array($v))
            addElements($xml->addChild($k), $v);
        else $xml->addAttribute($k,$v);
    }
    
    }
    function xml_encode($array)
    {
    if(!is_array($array))
        trigger_error("Type missmatch xml_encode",E_USER_ERROR);
    $xml=new SimpleXMLElement('<'.key($array).'/>');
    addElements($xml,$array[key($array)]);
    return $xml->asXML();
    } 
    

    You may want to add checks for length of the array so that some element get set inside the data part and not as an attribute.

提交回复
热议问题