如何取消 php 中的 xml 元素?

How to unset xml elements in php?

我正在编写如下所示的 php 代码,我希望在 php 中取消设置 xml 元素。

我按以下方式应用了逻辑:

当 $a 为 4 时,它应该显示 xml 中从顶部开始的第 4 个项目。
当 $a 为 3 时,它应该显示 xml 中从顶部开始的第 3 个项目。
当 $a 为 2 时,它应该显示 xml 中从顶部开始的第 2 个项目。
当 $a 为 1 时,它应该显示 xml 中从顶部开始的第一项。

此时我将a的值设置为4。

$a=4;
if ($a == 1) {  // it would not unset item[0] and it should display item[0]   (April 5)
for($i = count($xml->channel->item); $i >= 1; $i--){
unset($xml->channel->item[$i]);                     
}
} else if ($a == 2) { // it would not unset item[1]  and it should display item[1] (April 4)
for($i = count($xml->channel->item); $i >= 2; $i--){
unset($xml->channel->item[$i]);
}
unset($xml->channel->item[0]);                 
} else if ($a == 3) { // it would not unset item[2] and it should display item[2]  (April 3)
for($i = count($xml->channel->item); $i >= 3; $i--){
unset($xml->channel->item[$i]);
}
unset($xml->channel->item[0]);
unset($xml->channel->item[1]);
} else if ($a == 4) { // it would not unset item[3] and it should display item[3]  (April 2)
for($i = count($xml->channel->item); $i >= 4; $i--){
unset($xml->channel->item[$i]);
}
unset($xml->channel->item[0]);
unset($xml->channel->item[1]);
unset($xml->channel->item[2]);
} else if ($a == 5) {  // it would not unset item[4] and it should display item[4]   (April 1)
unset($xml->channel->item[0]);
unset($xml->channel->item[1]);
unset($xml->channel->item[2]);
unset($xml->channel->item[3]);
}

以上代码无法正常运行。所有内容均来自此 xml http://www.cpac.ca/tip-podcast/jwplayer.xml

我附上了物品清单的截图。

如果要显示来自特定元素的信息,可以直接通过其索引访问它,而无需删除其他条目。此代码适用于从您问题中的 URL 下载的 XML。请注意,xml 元素数组是从 0 开始索引的,因此值 2 将获得数组中的第三个条目,因此我们使用 $a-1 以便值 3 对应于第三个条目。另请注意,由于某些子项具有不同的命名空间,因此略微复杂...

$xml = simplexml_load_string($xmlstr);
$a = 3;
$item = $xml->channel->item[$a-1];
echo "Title: " . $item->title . "\n";
echo "Description: " . $item->description . "\n";
$jw = $item->children('jwplayer', true);
echo "Image: " . $jw->image . "\n";
echo "Source: " . $jw->source->attributes()->file . "\n";

输出:

Title: April 3, 2019 
Description: Jody Wilson-Raybould and Jane Philpott are removed from the Liberal Caucus. Gerald Butts submits text messages, and other evidence, to the justice committee. The Environment Commissioner says Canada isn't doing enough to fight climate change. 
Image: http://media.cpac.ca/_app_images/tip_player_poster.png 
Source: http://www.cpac.ca/tip-podcast/1554286033.mp3

Demo on 3v4l.org