来自数组的帐户XML,包含成员

时间:2011-01-14 23:51:54

标签: php xml arrays

我确信此前已被问过,但很难找到正确的搜索字词。

我有一个阵列;这最终是从SQL查询构建的

$users = array('peter','megan','michael');

我想要结束的是每个用户的XML结构,其中数组中的其他用户是成员。像:

<accounts>
    <user>
        <uid>peter</uid>
        <members>
            <user>megan</user>
            <user>michael</user>
        </members>
    </user>
    <user>
        <uid>megan</uid>
        <members>
            <user>peter</user>
            <user>michael</user>
        </members>
    </user>
    <user>
        <uid>michael</uid>
        <members>
            <user>peter</user>
            <user>megan</user>
        </members>
    </user>
</accounts>

有人说明如何做到这一点?

1 个答案:

答案 0 :(得分:0)

<?php

$users = array('peter','megan','michael');

$accounts = new SimpleXmlElement('<accounts />');
foreach($users as &$uid) {
    $node = $accounts->addChild('user');
    $node->addChild('uid', $uid);
    $members = $node->addChild('members');
    foreach($users as &$member) if ($member != $uid){
        $members->addChild('user', $member);
    }
}
$xml = $accounts->asXml();