处理子节点的混合列表和 PHP foreach
我有一个如下所示的 XML 文件:
<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>
我正在使用 SimpleXML,并且需要对“item”和“label”节点的组合列表执行 foreach,忽略其余的“channel”子节点。
我正在使用:
foreach($feed->channel->item as $item) { }
...并且标签添加为:
<item type="label">
<title>LABEL 1</title>
</item>
...但是我正在构建的文件的使用者期望标签的节点。
更新!
由于问题没有发布(需要标题!),同时我自己找到了答案,这就是我所做的:
/* Search for items and labels */
$result = $iFeed->xpath('channel/*[name()="item" or name()="label"]');
foreach($result as $item) {
// boom
}
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您还可以使用
|
运算符。这结合了多个 XPath 查询的结果。看起来它还保留了节点的顺序,因此节点按以下顺序返回:“项目,标签,项目,标签,项目”(而不是“项目,项目,项目,标签,标签”)。
I think you can also use the
|
operator. This combines the results of multiple XPath queries.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").