我的问题是我只需要从这个xml文件中下载3,这样我就不需要10个但只需要3个,
代替我得到10我将只使用3,因为我想要3个关于文件内容的最新消息,因此我听说我如何才能使我只下载3个文件
<?php
$xml = simplexml_load_file("http://www.odin.dk/RSS/RSS.aspx?beredskabsID=d1d94661-0f60-4e67-aeff-304d22199f8a");
echo "<table id='alarm' cellpadding=\"0\" cellspacing=\"0\">";
echo "<tr>";
echo "<th>Melding</th>";
echo "<th>Tidspunkt</th>";
echo "<th>Dato</th>";
echo "</tr>";
foreach ($xml->children() as $child) {
foreach ($child as $c) {
if ($c->getname() == "item") {
echo "<tr>";
echo "<td>" . $c->description . "</td>";
echo "<td>" . $c->comments . "</td>";
$days = array("Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag");
$months = array("Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec");
$timestamp = strtotime($c->pubDate);
$dayInWeek = $days[date('N', $timestamp)-1];
$month = $months[date('n', $timestamp)-1];
$dayInMonth = date('d', $timestamp);
$year = date('Y', $timestamp);
echo "<td>$dayInWeek $dayInMonth $month $year</td>";
echo "</tr>";
}
}
}
echo "</table>";
?>
答案 0 :(得分:1)
如果你使用xpath的组合,只选择项目节点,然后使用array_slice来获得前3个,那么你可以在删除内部foreach时执行此操作:
<?php
$xml = simplexml_load_file("http://www.odin.dk/RSS/RSS.aspx?beredskabsID=d1d94661-0f60-4e67-aeff-304d22199f8a");
echo "<table id='alarm' cellpadding=\"0\" cellspacing=\"0\">";
echo "<tr>";
echo "<th>Melding</th>";
echo "<th>Tidspunkt</th>";
echo "<th>Dato</th>";
echo "</tr>";
foreach (array_slice($xml->xpath('/rss/channel[1]/item'), 0, 3) as $c) {
echo "<tr>";
echo "<td>" . $c->description . "</td>";
echo "<td>" . $c->comments . "</td>";
$days = array("Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag");
$months = array("Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec");
$timestamp = strtotime($c->pubDate);
$dayInWeek = $days[date('N', $timestamp)-1];
$month = $months[date('n', $timestamp)-1];
$dayInMonth = date('d', $timestamp);
$year = date('Y', $timestamp);
echo "<td>$dayInWeek $dayInMonth $month $year</td>";
echo "</tr>";
}
echo "</table>";
?>
答案 1 :(得分:0)
为什么不添加一个计数器,如果它的3然后打破循环。
$i = 0;
foreach ($child as $c) {
if ($c->getname() == "item") {
// code
if ($i == 3) break;
// display code
$i++ ;
}
}