这是我用来通过html dom php删除数据并以表格形式回显数据的代码 所有数据都以完美的表格形式出现。但是我想在table.at中显示所有数据回显中只有5个最后我使用表来回显一个内容或数据我想只回显5个数据显示出来但我不知道编码这个...任何人都可以帮我这么做吗?
<?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><a href="' . $eventLink . '" title="' . $img->textContent . '">' . $img->textContent . '</a></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>';
?>
答案 0 :(得分:2)
您要限制哪一个循环?无论哪一个,结构都是一样的。像这样:
$i = 0;
foreach ($collection as $item) {
$i++;
if ($i > 5) {
break;
}
// the rest of your loop code
}
所以你基本上存储在$i
(或你想要调用变量的任何东西)中循环执行次数的计数。 5次之后,无论剩下多少记录,都使用break;
退出循环。