ropadope
ropadope

Reputation: 81

Dealing with mixed list of child nodes and PHP foreach

I have an XML file that looks like this:

<rss>
    <channel>
        <title>title</title>
        <link>link</link>
        <description>description</description>
        <item>
            <title>title 1</title>
            <sort>1</sort>
        </item>
        <label>
            <title>LABEL 1</title>
            <sort>2</sort>            
        </label>
        <item>
            <title>title 2</title>
            <sort>3</sort>
        </item>
        <label>
            <title>LABEL 2</title>
            <sort>4</sort>            
        </label>
        <item>
            <title>title 3</title>
            <sort>5</sort>
        </item>
        <template>3</template>
    </channel>
</rss>

I'm using SimpleXML and I need to do a foreach on the combined list of 'item' and 'label' nodes, ignoring the rest of the 'channel' children.

I was using:

foreach($feed->channel->item as $item) { }

...and labels were added as:

<item type="label">
    <title>LABEL 1</title>
</item>

...but the consumer of the file I'm building is expecting the node for labels.


UPDATE!

As the question didn't get posted (need a title!) and I found the answer on my own in the meantime here's what I did:

/* Search for items and labels */
$result = $iFeed->xpath('channel/*[name()="item" or name()="label"]');

foreach($result as $item) {
   // boom
}

Upvotes: 0

Views: 221

Answers (1)

Michael
Michael

Reputation: 35341

I think you can also use the | operator. This combines the results of multiple XPath queries.

$result = $root->xpath('channel/item|channel/label');

It looks like it also preserves the ordering of the nodes, so the nodes are returned in this order: "item, label, item, label, item" (as opposed to "item, item, item, label, label").

Upvotes: 2

Related Questions