【发布时间】:2019-08-27 19:36:30
【问题描述】:
我正在编写如下所示的 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 中提取出来
我已附上项目列表的屏幕截图。
【问题讨论】:
-
如果你只想显示第n个元素为什么你需要取消设置它之前的所有元素?
-
@Nick 你能在回答中告诉我我需要做哪些修改吗?
-
你就不能
echo $xml->channel->item[$a];吗? -
喜欢这个
if ($a == 1) { echo $xml->channel->item[$a]; } -
@Nick 你在吗?
标签: php xml xml-parsing unset