提问者:小点点

创建带有属性的xml表单php


这是我的代码为XML数组,但它重叠的项目。

function to_xml(SimpleXMLElement $object, array $data) {
$attr = "Attribute_";
foreach ($data as $key => $value) {
    
    if (is_array($value)) {
        $new_object = $object->addChild($key);
        to_xml($new_object, $value);
    } else {
        if(strpos($key, $attr) !== false){
            $object->addAttribute(substr($key, strlen($attr)), $value);
        }else{
            $object->addChild($key, $value);
        }
    }
}
}

$my_array = array (
'item' => array(
    'Attribute_ID' => '123',
    'Attribute_key' => 'a',
    'Attribute_tel' => '01',
),
'item' => array(
    'Attribute_ID' => '124',
    'Attribute_key' => 'b',
    'Attribute_tel' => '02',
)
);

$xml = new SimpleXMLElement('<root/>');
to_xml($xml, $my_array);
Header('Content-type: text/xml');
print($xml->asXML());

我们希望输出像

<?xml version="1.0"? >
<root>
<item ID="123" key="a" tel="01"/>
<item ID="124" key="b" tel="02"/>
</root>

当前代码显示oputput类似

<?xml version="1.0"?>
<root>
<item ID="124" key="b" tel="02"/>
</root>

它覆盖item元素。


共1个答案

匿名用户

创建要添加的项数组。 如果您可以接受不使用to_xml()函数:

<?php
$items = array(
    array(
        'ID' => '123',
        'key' => 'a',
        'tel' => '01',
    ),
    array(
        'ID' => '124',
        'key' => 'b',
        'tel' => '02',
    ),
);

$xml = new SimpleXMLElement('<root/>');
foreach ($items as $item) {
    $xmlItem = $xml->addChild('item');
    foreach ($item as $key => $attribute) {
        $xmlItem->addAttribute($key, $attribute);
    }
}

header('Content-type: text/xml');
print($xml->asXML());

将输出:

<?xml version="1.0"?>
<root><item ID="123" key="a" tel="01"/><item ID="124" key="b" tel="02"/></root>