Reputation: 23
my problem is such that I only need to download 3 from this xml file, and it is such that I do not need 10 but only 3 of them,
in place of that I get 10 I will only use 3 because I want the 3 latest news about what is in the file, therefore I hear about how I make it possible that I only download 3 files
<?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>";
?>
Upvotes: 1
Views: 270
Reputation: 44844
Why not add a counter and if its 3 then break the loop.
$i = 0;
foreach ($child as $c) {
if ($c->getname() == "item") {
// code
if ($i == 3) break;
// display code
$i++ ;
}
}
Upvotes: 0
Reputation: 711
If you use a combination of xpath, to select only the item nodes, and then array_slice to get just the first 3 then you can do this while removing your inner 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>";
?>
Upvotes: 1