PHP Simple XML基于其属性获取节点

时间:2014-03-26 14:41:22

标签: php xml simplexml

我创建了一个XML文件,其中包含特许经营的结构化列表。问题是我想通过它的ID获取特许经营权,而不必遍历整个列表。

这就是我如何获得第一个特许经营权的属性。但我想取回一个名为'3'的特许经营对象。我会认为id是关键但不是,见下文:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 1
            [name] => Franchise 1
            [aid] => 
        )

)

以下是我访问第一个特许经营权属性的方法,但这对我没有多大帮助。

$this->xmlData->franchises->franchise->attributes()

这是xml的结构

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <franchises>
        <franchise id="1" name="Franchise 1" >
            <header>
                <accountId>2354435435</accountId>
            </header>
            <used-list>
                <accountId>2354435435</accountId>
            </used-list>
            <used-detail>
                <accountId>2354435435</accountId>
            </used-detail>
            <contact-us>
                <accountId>2354435435</accountId>
            </contact-us>
            <new-detail>
                <accountId>2354435435</accountId>
            </new-detail>
            <left-column>
                <accountId>2354435435</accountId>
            </left-column>
            <new-list>
                <accountId>2354435435</accountId>
            </new-list>
            <offer-detail>
                <accountId>2354435435</accountId>
            </offer-detail>
            <popup>
                <accountId>2354435435</accountId>
            </popup>
        </franchise>
        <franchise id="2" name="Franchise 2" >
            <header>
                <accountId>2354435435</accountId>
            </header>
            <used-list>
                <accountId>2354435435</accountId>
            </used-list>
            <used-detail>
                <accountId>2354435435</accountId>
            </used-detail>
            <contact-us>
                <accountId>2354435435</accountId>
            </contact-us>
            <new-detail>
                <accountId>2354435435</accountId>
            </new-detail>
            <left-column>
                <accountId>2354435435</accountId>
            </left-column>
            <new-list>
                <accountId>2354435435</accountId>
            </new-list>
            <offer-detail>
                <accountId>2354435435</accountId>
            </offer-detail>
            <popup>
                <accountId>2354435435</accountId>
            </popup>
        </franchise>
    </franchises>
</data>

非常感谢帮助。

1 个答案:

答案 0 :(得分:2)

看看xpath。您可以按以下属性检索特定节点:

$result = $xml->xpath("//franchises/franchise[@id='2']");