SimpleXMLElement文档 - 如何在SimpleXMLElement对象中返回子属性的值?

时间:2012-09-07 00:14:12

标签: php object simplexml

这是XML:

<Routes>
    <Route type="source">
        <Table>
            <Tablename>incoming</Tablename>
            <Fields>
                <Fieldsname ref="description" name="Route Name">description</Fieldsname>
                <Fieldsname name="CID Match">cidnum</Fieldsname>
                <Fieldsname name="DID Match">extension</Fieldsname>
                <Fieldsname ref="dest">destination</Fieldsname>
            </Fields>
        </Table>

    </Route>
</Routes>

然后我在PHP中实例化它:

$doc    = new SimpleXMLElement('routingConfig.xml', null, true);

print_r($doc->Route[0])显示了这一点:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [type] => source
        )

    [comment] => SimpleXMLElement Object
        (
        )

    [Table] => SimpleXMLElement Object
        (
            [Tablename] => incoming
            [comment] => SimpleXMLElement Object
                (
                )

            [Fields] => SimpleXMLElement Object
                (
                    [Fieldsname] => Array
                        (
                            [0] => description
                            [1] => cidnum
                            [2] => extension
                            [3] => destination
                        )

                    [comment] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                )

                            [1] => SimpleXMLElement Object
                                (
                                )

                        )

                )

        )

)

注意根值是如何包含@attributes数组的。为什么$doc->Routes[0]->Table->Fields->Fieldsname没有@attributes?我知道我可以通过attributes()获取它,但有没有办法让它包含在$doc中?

修改 显然print_r()没有在数组/对象中显示每个值,探索所有孩子等等。或者SimpleXMLElement除非请求,否则$doc不会返回它(似乎应该全部存储在print_r($doc->Route[0]->Table->Fields->Fieldsname[0]);)中。如果您执行SimpleXMLElement Object ( [@attributes] => Array ( [ref] => description [name] => Route Name ) [0] => description ) ,则会返回

print_r($doc->Route[0]->Table->Field);

显示我正在寻找的数据。但是,如果我执行{{1}},则不会显示数据。

1 个答案:

答案 0 :(得分:1)

SimpleXMLElement对象在PHP中做了一些非常高级的事情。它实现了许多PHP提供的“魔术”钩子,因此它可以在foreach()之类的东西中运行,并且被视为“黑盒子”。因此,在其上使用print_r()会给您带来误导性和不完整的信息。您不能依赖于print_r()对象上的var_dump()(或SimpleXMLElement)。

SimpleXMLElement中调试结构的方法是简单地查找您所追求的元素:例如isset($xmlnode->child)之类的东西。所以is_array($doc->Route[0]->Table->Fields->Fieldsname)将是真的。