drpiqlzrh62917192 2011-04-27 16:48
浏览 28
已采纳

处理子节点和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
}
  • 写回答

1条回答 默认 最新

  • dongqing7789 2011-04-27 17:10
    关注

    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").

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类