Limiting the number of feed items displayed - php

Below is roughly what I am using to display items from a feed. It works fine but the feed has many items and I want to be able to just display the first 5 items in the feed. How can this e done?
<?php
$theurl = 'http://www.theurl.com/feed.xml';
$xml = simplexml_load_file($theurl);
$result = $xml->xpath("/items/item");
foreach ($result as $item) {
$date = $item->date;
$title = $item->title;
echo 'The title is '. $title.' and the date is '. $date .'';
} ?>

foreach ($result as $i => $item) {
if ($i == 5) {
break;
}
echo 'The title is '.$item->title.' and the date is '. $item->date;
}

A for loop may be more suitable for this than a foreach loop:
for ($i=0; $i<=4; $i++) {
echo 'The title is '.$result[$i]->title.' and the date is '. $result[$i]->date;
}
This loop has a much higher performance when not modifying anything in the array, so if speed matters I'd recommend it.

Just do it as part of the XPath query:
<?php
$theurl = 'http://www.theurl.com/feed.xml';
$xml = simplexml_load_file($theurl);
$result = $xml->xpath('/items/item[position() <= 5]');
foreach ($result as $item) {
$date = $item->date;
$title = $item->title;
echo 'The title is '. $title.' and the date is '. $date . '';
}
?>
Here's a demo!

Related

how to filter data from html table

This is a code i used to prase a data through html dom php and echo a data in table form
all data came in perfect table form. but i want to show only 5 out of all data echo in table.at last i used table to echo a content or data i want only to echo 5 data out of all showing out but i am not getting any idea to code this.. any one can help me to do this?
<?php
include('simple_html_dom.php');
$html = file_get_html('http://www.discoverhongkong.com/us/see-do/events-festivals/events-calendar/index.jsp');
$eventRowData = array();
class eventRecord
{
public $dates;
public $eventDescription;
}
;
foreach ($html->find('#event_table tr') as $eventItem) {
$eventDateArray = array();
$oneEventData = new eventRecord;
foreach ($eventItem->find('.date') as $eventDate) {
$oneDateData = array();
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($eventDate);
$dom->preserveWhiteSpace = true;
$hTwo = $dom->getElementsByTagName('div')->item(0);
foreach ($hTwo->childNodes as $dateElement) {
array_push($oneDateData, $dateElement->nodeValue);
}
//print_r ($oneDateData);
array_push($eventDateArray, $oneDateData);
}
//
$oneEventData->dates = $eventDateArray;
$eventData = null;
foreach ($eventItem->find('.event_name') as $eventName) {
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($eventName);
$dom->preserveWhiteSpace = true;
$baseLink = "http://www.discoverhongkong.com";
$img = $dom->getElementsByTagName('a')->item(0);
$relativeLink = $img->attributes->getNamedItem("href")->value;
$eventLink = $baseLink . $relativeLink;
$eventData = '<strong>' . $img->textContent . '</strong><br />';
$oneEventData->eventDescription = $eventData;
//echo $oneEventData->eventDescription;
}
array_push($eventRowData, $oneEventData);
}
$arr = array_values($eventRowData);
//Print_r ($eventRowData);
//echo "----------";
//echo $arr[0]->eventDescription;
//echo "----------";
echo '</br>';
echo '<h2>Events In HongKong</h2>';
echo '<table class="table-bordered">';
echo '<tr>';
echo '<th class="abc">EVENT NAME</th>';
echo '<th>START DATE</th>';
echo '<th>END DATE</th>';
echo '</tr>';
foreach ($arr as $xyz) {
//print_r ($xyz);
echo '<tr>';
echo '<td>';
echo ($xyz->eventDescription);
echo '</td>';
//$mydates = array_values($xyz->dates);
//print_r ($mydates);
foreach ($xyz->dates as $datevalue) {
//echo '<tr>';
echo '<td>';
foreach ($datevalue as $datevalueitem) {
echo $datevalueitem;
echo '/';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
?>
Which of these loops is the one you want to restrict? Whichever one it is, the structure would be the same. Something like this:
$i = 0;
foreach ($collection as $item) {
$i++;
if ($i > 5) {
break;
}
// the rest of your loop code
}
So you're basically storing in $i (or whatever you want to call the variable) a count of how many times the loop has executed. After 5 times, you use break; to exit the loop, regardless of how many records remain.

For Loop without second condition [duplicate]

This question already has answers here:
Loop a multidimensional array and only print two specific column values per row
(6 answers)
Closed 5 years ago.
<?php
$val = $_GET["val"];
$url = "http://feeds.bbci.co.uk/news/rss.xml";
$xml = simplexml_load_file($url);
for($i = 0; $i < 10 ; $i++){
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$description = $xml->channel->item[$i]->description;
$pubDate = $xml->channel->item[$i]->pubDate;
$rss .= "<a href='$link'><h3>$title</h3></a>";
$rss .= "$description";
$rss .= "<br />$pubDate<hr />";
}
echo $rss;
?>
Hello everyone! I have a problem here. I would like to list all the results for the rss link but it gets only 10. I know that I have the second condition for "for loop" as $i<10, but how can I remove that condition, and get all the results from the rss link?
Use foreach instead of for:
<?php
$url = "http://feeds.bbci.co.uk/news/rss.xml";
$xml = simplexml_load_file($url);
$rss = '';
foreach ($xml->channel->item as $item) {
$title = $item->title;
$link = $item->link;
$description = $item->description;
$pubDate = $item->pubDate;
$rss .= "<a href='$link'><h3>$title</h3></a>";
$rss .= "$description";
$rss .= "<br />$pubDate<hr />";
}
echo $rss;
?>
Either you can use foreach loop or count the size of an array and then use this size to set the second condition in your for loop..

How to compare values in a loop?

I have orders come in. Each order has a type i.e 'Vanilla' and a size i.e 'Mini with a quantity.
If there are 5 Mini Vanillas I want it to display once not 5 times. I also want to tally the quantity.
Here is one of the many things I attempted
$prevSize = null;
$prevType= null;
foreach ($orders as $order){
echo '<tr>';
$new_order = new WC_Order();
$order_items = $new_order->get_items();
foreach ($order_items as $order_item ){
$currentSize = $order_item['pa_size'];
$currentType = wp_get_post_terms( $order_item['product_id'],'pa_ct');
$currentType = $currentType[0]->name;
if($prevSize != $currentSize){
echo $currentType . '<br>';
echo $currentSize . '<br>';
}
$count += $order_item['qty'];
echo $count;
}
$prevSize = $currentSize;
$prevType = $currentType;}
We have analyzed your query, and according to your need, here is my solution:
$order_type = array();
foreach ($orders as $order){
echo '<tr>';
$new_order = new WC_Order();
$order_items = $new_order->get_items();
$count = 0;
foreach ($order_items as $order_item ){
$currentSize = $order_item['pa_size'];
$currentType = wp_get_post_terms( $order_item['product_id'],'pa_ct');
$currentType = $currentType[0]->name;
$temp_order_type = $currentSize.'_'.$currentType;
if(!in_array($temp_order_type, $order_type)){
$order_type[] = $temp_order_type;
echo $currentType . '<br>';
echo $currentSize . '<br>';
}
$count += $order_item['qty'];
}
echo $count;
}
Above code will display each order type once not display multiple times. And display the quantity ordered in each order.

About Limiting Rss Feed

I want only the latest 5 feeds to be shown on my website.
I am using the following code to fetch rss feed... Can any one help to limited feeds to be shown... Thank You In ADVANCE :)
CODE THAT AM USING
<?php
require_once('rss_fetch.inc');
$url = 'http://news.google.com/news?ned=us&topic=h&output=rss';
$rss = fetch_rss($url);
echo "Site: ", $rss->channel['title'], "<br>\n";
foreach ($rss->items as $item ) {
$title = $item['title'];
$url = $item['link'];
$desc = $item['description'];
$category = $item['category'];
echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
}
?>
Limit it using foreach?
foreach ($rss->items as $i => $item ) { // use $i as counter
$title = $item['title'];
$url = $item['link'];
$desc = $item['description'];
$category = $item['category'];
echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
if($i == 4) break; // add this, == 4 is because $i starts from 0
}
If you're looking to limit the number of posts, you just need to keep track of them and break out of the foreach loop when applicable, e.g.
<?php
require_once('rss_fetch.inc');
$url = 'http://news.google.com/news?ned=us&topic=h&output=rss';
$rss = fetch_rss($url);
echo "Site: ", $rss->channel['title'], "<br>\n";
$numposts = 0;
$maxposts = 5;
foreach ($rss->items as $item ) {
$numposts++;
if ($numposts<=$maxposts) {
$title = $item['title'];
$url = $item['link'];
$desc = $item['description'];
$category = $item['category'];
echo "<a href=$url>$title</a>$desc <br/>CATEGORY : $category <br/><br/> ";
} else {
break;
}
}
?>

PHP loop, change last item?

This might actually be a css question but I'm hoping not because I'd like this to work in IE.
I have the following loop:
<?php
if ($category)
{
foreach($category as $item)
{
echo $item['name'];
echo ", ";
}
} ?>
Which should output
item, item, item, item,
The only thing is...I'd like to NOT have a comma after the last item. Is there any way to do this within a loop?
Well to keep your code how it is, you could add a counter, and skip the last one.
<?php
if ($category) {
$counter = 0;
foreach($category as $item)
{
$counter++;
echo $item['name'];
if ($counter < count($category)) {
echo ", ";
}
}
}
?>
Or you can do it much, much, quicker:
<?php echo implode(", ", array_map(create_function('$item', 'return $item["name"];'), $category)); ?>
Don't echo immediately but save your output into a variable that you can trim.
<?php
if ($category) {
$output = '';
foreach($category as $item) {
$output .= $item['name'];
$output .= ", ";
}
echo rtrim($output, ', ');
}
?>
The implode solution is the simplest, but you asked for a loop. This method avoids putting an extra conditional in the loop, and therefore should be somewhat more efficient. Basically, instead of doing something different for the last item, you do something different for the first item.
$myArray = array(); //Fill with whatever
$result = $myArray[0];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx];
}
EDIT: After realizing you want $item['name'] instead of just $item:
$myArray = array(); //Fill with whatever
$result = $myArray[0]['name'];
for ($idx = 1; $idx < count($myArray); $idx += 1)
{
$result .= ', ' . $myArray[$idx]['name'];
}
As lovely as foreach is,...
<?php
if ($category) {
$count = count($category) - 1;
for ($i = 0; $i <= $count; $i++) {
echo $category[$i]['name'];
if ($i < $count)
echo ', ';
}
}
?>
...for is sometimes necessary.
Assuming $category is an array, you can use implode to get what you want:
Edit: Missed the $categories['name'] part, this should work:
<?php implode(", ", array_keys($category, 'name')); ?>
The standard solution to the "last comma" problem is to put items into an array and then implode it:
$temp = array();
foreach($category as $item)
$temp[] = $item['name'];
echo implode(', ', $temp);
If you want this more generic, you can also write a function that picks ("plucks") a specific field out of each subarray:
function array_pluck($ary, $key) {
$r = array();
foreach($ary as $item)
$r[] = $item[$key];
return $r;
}
and then just
echo implode(', ', array_pluck($category, 'name'));
Or you could check for the last key:
end($category);
$lastkey = key($category);
foreach ( $category AS $key => $item ) {
echo $item['name'];
if ( $lastkey != $key ) {
echo ', ';
}
}
And another option:
<?php
$out = "";
foreach ($category as $item)
{
$out .= $item['name']. ", ";
}
$out = preg_replace("/(.*), $/", "$1", $out);
echo $out;
?>

Categories