How to convert array to SimpleXML

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

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

30条回答
  •  感动是毒
    2020-11-21 07:19

    Another improvement:

    /**
    * Converts an array to XML
    *
    * @param array $array
    * @param SimpleXMLElement $xml
    * @param string $child_name
    *
    * @return SimpleXMLElement $xml
    */
    public function arrayToXML($array, SimpleXMLElement $xml, $child_name)
    {
        foreach ($array as $k => $v) {
            if(is_array($v)) {
                (is_int($k)) ? $this->arrayToXML($v, $xml->addChild($child_name), $v) : $this->arrayToXML($v, $xml->addChild(strtolower($k)), $child_name);
            } else {
                (is_int($k)) ? $xml->addChild($child_name, $v) : $xml->addChild(strtolower($k), $v);
            }
        }
    
        return $xml->asXML();
    }
    

    Usage:

    $this->arrayToXML($array, new SimpleXMLElement(''), 'child_name_to_replace_numeric_integers');
    

提交回复
热议问题