How to convert array to SimpleXML

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

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

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 07:08

    I use a couple of functions that I wrote a while back to generate the xml to pass back and forth from PHP and jQuery etc... Neither use any additional frameworks just purely generates a string that can then be used with SimpleXML (or other framework)...

    If it's useful to anyone, please use it :)

    function generateXML($tag_in,$value_in="",$attribute_in=""){
        $return = "";
        $attributes_out = "";
        if (is_array($attribute_in)){
            if (count($attribute_in) != 0){
                foreach($attribute_in as $k=>$v):
                    $attributes_out .= " ".$k."=\"".$v."\"";
                endforeach;
            }
        }
        return "<".$tag_in."".$attributes_out.((trim($value_in) == "") ? "/>" : ">".$value_in."" );
    }
    
    function arrayToXML($array_in){
        $return = "";
        $attributes = array();
        foreach($array_in as $k=>$v):
            if ($k[0] == "@"){
                // attribute...
                $attributes[str_replace("@","",$k)] = $v;
            } else {
                if (is_array($v)){
                    $return .= generateXML($k,arrayToXML($v),$attributes);
                    $attributes = array();
                } else if (is_bool($v)) {
                    $return .= generateXML($k,(($v==true)? "true" : "false"),$attributes);
                    $attributes = array();
                } else {
                    $return .= generateXML($k,$v,$attributes);
                    $attributes = array();
                }
            }
        endforeach;
        return $return;
    }   
    

    Love to all :)

提交回复
热议问题