解析XML文件时Foreach语句仅输出一条记录

发布于 2024-11-28 11:50:16 字数 692 浏览 0 评论 0原文

我正在尝试解析 XML 文件,以便从以“b”开头的 标记中获取所有记录,如下所示:

在此处输入图像描述

xml 文件的链接为:

http://www.bbc.co.uk/radio1/programmes/schedules/ england.xml

到目前为止,我的代码是:

<?php

$xml = simplexml_load_file('http://www.bbc.co.uk/radio1/programmes/schedules/england.xml');
foreach($xml->day>broadcasts->broadcast as $pid){
echo $pid->programme->pid;
}
?>

据我所知,这个 foreach 语句 应该回显所有 pid 记录,而它只执行第一个记录。

关于我的代码在哪里出错以及如何让它输出所有这些代码有什么想法吗?

I am trying to parse an XML file so that I get all of the records from the <pid> tags that start with a 'b' as shown:

enter image description here

The link to the xml file is:

http://www.bbc.co.uk/radio1/programmes/schedules/england.xml

And the code I have so far is:

<?php

$xml = simplexml_load_file('http://www.bbc.co.uk/radio1/programmes/schedules/england.xml');
foreach($xml->day>broadcasts->broadcast as $pid){
echo $pid->programme->pid;
}
?>

As far as my knowledge goes, this foreach statement should echo out all of the pid records, where it only does the first one.

Any ideas on where my code is going wrong as to how I make it output all of them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

↙温凉少女 2024-12-05 11:50:16

您的循环需要更深一层,因为 programme 节点是单个 broadcast 节点的多个子节点。因此,您需要循环遍历每个 broadcast 节点中的所有 programme 节点,以回显它们的 pid

foreach($xml->day>broadcasts->broadcast as $broadcast){

  // Loop over all <programme> contained in each <broadcast>
  foreach ($broadcast->programme as $prog) {
    echo $prog->pid;
  }
}

Your loop needs to go one level deeper, since the programme nodes are multiple children of a single broadcast node. You therefore need to loop over all the programme nodes in each broadcast node to echo out their pid

foreach($xml->day>broadcasts->broadcast as $broadcast){

  // Loop over all <programme> contained in each <broadcast>
  foreach ($broadcast->programme as $prog) {
    echo $prog->pid;
  }
}
绿光 2024-12-05 11:50:16

您正在迭代整个 xml 结构,其中仅包含一个“day”节点。

您应该首先将“光标”定位在您希望迭代的元素的父元素上:

<?php 

$xml = simplexml_load_file('http://www.bbc.co.uk/radio1/programmes/schedules/england.xml');
$broadcasts = $xml->day->broadcasts;
foreach($broadcasts->broadcast as $bc) {
    echo $bc->programme->pid;
}

you are iterating over whole xml structure, which contains only one "day" node.

you should position your "cursor" first on the parent of the elements you wish to iterate on :

<?php 

$xml = simplexml_load_file('http://www.bbc.co.uk/radio1/programmes/schedules/england.xml');
$broadcasts = $xml->day->broadcasts;
foreach($broadcasts->broadcast as $bc) {
    echo $bc->programme->pid;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文