如何获取xml元素的值?

时间:2010-05-17 14:07:21

标签: php xml simplexml

我有一些xml数据,我正在尝试访问一些元素。数据结构 如下(使用print_r($ data))。 我可以得到$data->{'parent'}->title,它可以工作,但是如果我试图获得href的值 $data->{'parent'}->link[0]->{'@attributes'}->href ..它不起作用..任何想法?

由于

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [children] => 29
            [modules] => 0
        )
[title] => Test title
[link] => Array
    (
        [0] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [href] => data.php?id=2322
                        [rel] => self
                        [type] => application/xml
                    )

            )

        [1] => SimpleXMLElement Object
            (
                [@attributes] => Array
                    (
                        [href] => data.php?id=2342
                        [rel] => alternate
                        [type] => text/html
                    )

            )

    )

[parent] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [children] => 6
                [modules] => 0
            )

        [title] => Top
        [link] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [href] => /data.php?id=5763
                                [rel] => self
                                [type] => application/xml
                            )

                    )

                [1] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [href] => /data.php?id=2342
                                [rel] => alternate
                                [type] => text/html
                            )

                    )

            )

    )

2 个答案:

答案 0 :(得分:2)

查看Accessing @attribute from SimpleXML,尤其是对SimpleXML Objects的误导性var_dumpprint_r)输出的评论。

那就是说,IIRC应该在你的例子中起作用:

$data->{'parent'}->link[0]['href']

(也就是说,可以使用标准数组表示法访问属性 - 这肯定适用于单个元素,不确定它是否与元素集合中的附加索引一起使用。)

答案 1 :(得分:1)

不要使用print_r()来检查SimpleXMLElement。相反,只需看看XML。使用对象表示法->name访问子项,并使用数组表示法['name']访问属性。

在您的情况下,我想访问此属性的正确方法是

$data->parent->link[0]['href']
相关问题