如何在php中取消设置xml元素?

问题描述 投票:0回答:1

我正在开发一个PHP代码,如下所示,我想在php中设置未设置的xml元素。

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

当$ a为4时,它应显示xml顶部的第4项。 当$ a为3时,它应显示xml顶部的第3项。 当$ a为2时,它应该从xml的顶部显示第二项。 当$ 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中提取的

我已将截图附加到项目列表中。

enter image description here

php xml xml-parsing unset
1个回答
3
投票

如果要显示特定元素的信息,可以直接通过索引访问它,而不删除其他条目。此代码适用于从您的问题中的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

© www.soinside.com 2019 - 2024. All rights reserved.