How to convert array to SimpleXML

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

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

30条回答
  •  一整个雨季
    2020-11-21 07:29

    function array2xml(array $data, SimpleXMLElement $object = null, $oldNodeName = 'item')
    {
        if (is_null($object)) $object = new SimpleXMLElement('');
        $isNumbered = true;
        $idx = 0;
        foreach ($data as $key => $x)
            if (is_string($key) || ($idx++ != $key + 0))
                $isNumbered = false;
        foreach ($data as $key => $value)
        {   
            $attribute = preg_match('/^[0-9]/', $key . '') ? $key : null;
            $key = (is_string($key) && !preg_match('/^[0-9]/', $key . '')) ? $key : preg_replace('/s$/', '', $oldNodeName);
            if (is_array($value))
            {
                $new_object = $object->addChild($key);
                if (!$isNumbered && !is_null($attribute)) $new_object->addAttribute('id', $attribute);
                array2xml($value, $new_object, $key);
            }
            else
            {
                if (is_bool($value)) $value = $value ? 'true' : 'false';
                $node = $object->addChild($key, htmlspecialchars($value));
                if (!$isNumbered && !is_null($attribute) && !isset($node->attributes()->id))
                    $node->addAttribute('id', $attribute);
            }
        }
        return $object;
    }
    

    This function returns for example a list of ...... XML tags for numeric indexes.

    Input:

        array(
        'people' => array(
            'dog',
            'cat',
            'life' => array(
                'gum',
                'shoe',
            ),
            'fish',
        ),
        array('yeah'),
    )
    

    Output:

    
        
            dog
            cat
            
                gum
                shoe
            
            fish
            
                yeah
            
        
    
    

    This should satisfy all common needs. Maybe you may change the 3rd line to:

    $key = is_string($key) ? $key : $oldNodeName . '_' . $key;
    

    or if you are working with plurals ending with s:

    $key = is_string($key) ? $key : preg_replace('/s$/', '', $oldNodeName);
    

提交回复
热议问题