How to convert array to SimpleXML

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

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

30条回答
  •  你的背包
    2020-11-21 07:19

    IF the array is associative and keyed correctly, it would probably be easier to turn it into xml first. Something like:

      function array2xml ($array_item) {
        $xml = '';
        foreach($array_item as $element => $value)
        {
            if (is_array($value))
            {
                $xml .= "<$element>".array2xml($value)."";
            }
            elseif($value == '')
            {
                $xml .= "<$element />";
            }
            else
            {
                $xml .= "<$element>".htmlentities($value)."";
            }
        }
        return $xml;
    }
    
    $simple_xml = simplexml_load_string(array2xml($assoc_array));
    

    The other route would be to create your basic xml first, like

    $simple_xml = simplexml_load_string("");
    

    and then for each part of your array, use something similar to my text creating loop and instead use the simplexml functions "addChild" for each node of the array.

    I'll try that out later and update this post with both versions.

提交回复
热议问题