在simplexml中重新获取子节点的问题

时间:2011-02-12 18:01:34

标签: php xml simplexml

如果我有这个xml:

<field name="gender" type="select1">
    <label>Gender</label>
    <item>
        <label>Male</label>
        <value>1</value>
    </item>
    <item>
        <label>Female</label>
        <value>2</value>
    </item>
    <constraints>
        <required/>
    </constraints>
</field>

假设我必须获取每个项目标签并创建一个html表单。我怎么能使用simplexml文件print_r的xml对象显示这个:

[item] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [label] => Male
                                    [value] => 1
                                )

                            [1] => SimpleXMLElement Object
                                (
                                    [label] => Female
                                    [value] => 2
                                )

                        )

但在我的代码中

foreach($xml as $field) 
    {
        $type = $xml->field[$i]->attributes()->type ; 
        $name = $xml->field[$i]->attributes()->name ;
        $required = $xml->field[$i]->constraints[0]->required[0] ;



            //checkboxes and radios 
            echo $xml->field[$i]->lable ; 
            //check the lable 
            if(is_array($xml->field[$i]->item))
            {
                echo 'yes it\'s a array ' ; 
            }






        $i++ ; 
    }

使用此代码

if ($type == 'select1' || $type == 'radio') {
        foreach ($field->item as $item) {
            echo "{$item->label} = {$item->value}\n";
        }
    }

实际上还有另一组字段标签由项目标签组成,因此第二个foreach循环将被忽略

 <field name="language" type="select">
            <label>Language(s)</label>
            <item>
                <label>English</label>
                <value>1</value>
            </item>
            <item>
                <label>French</label>
                <value>2</value>
            </item>
            <item>
                <label>Persian</label>
                <value>4</value>
            </item>
            <constraints/>
        </field>

1 个答案:

答案 0 :(得分:0)

你必须做这样的事情:

$sxml = new SimpleXMLElement($xml);
foreach ($sxml->field as $field) {
    $label = $field->label;
    $type = $field['type'];
    $name = $field['gender'];
    $required = isset($field->constraints->required);

    if ($type == 'select1' || $type == 'radio') {
        foreach ($field->item as $item) {
            echo "{$item->label} = {$item->value}\n";
        }
    }
}

如果没有任何<items>个节点,则会忽略第二个foreach。您无需明确检查它。