我有以下代碼,它顯示日歷 XML 提要,但是,并非所有事件都有開始/結束時間。這會導致錯誤。我想當一個事件沒有開始和結束時間時,它會顯示“全天”。
//load xml file
$sxml = simplexml_load_file($url) or die("Error: Cannot create object");
echo '<div >';
#search for all event start dates
$starts = $sxml->xpath('//event/startdate');
#get the unique start dates of these event
$dates = array_unique($starts);
foreach($dates as $date) {
echo "<li><h1>{$date}</h1></li>" ."\n";
#search for all events taking place on each start date
$expression = "//event/startdate[.='{$date}']";
$events = $sxml->xpath($expression);
#iterate through these events and find their description
foreach ($events as $event){
echo "\t" , "<li><div class='time'>{$event->xpath('./following-sibling::starttime')[0]} - {$event->xpath('./following-sibling::endtime')[0]}</div><div class='event'><b> {$event->xpath('./following-sibling::description')[0]}</b> // {$event->xpath('./following-sibling::category')[0]}</div></li>";
echo "\n";
}
echo "\n";
}
echo "</div>";
下面的示例 XML 檔案:
<event>
<startdate>24/11/2021</startdate>
<alldayevent>true</alldayevent>
<description>Event 1</description>
<category>Main Events</category>
</event>
<event>
<startdate>24/11/2021</startdate>
<alldayevent>false</alldayevent>
<starttime>14:00</starttime>
<endtime>16:30</endtime>
<description>Event 2</description>
<category>Main Events</category>
</event>
預期輸出:
如果事件有 time/alldayevent = true 則顯示開始和結束時間,否則如果 alldayevent = true,則輸出“全天”
uj5u.com熱心網友回復:
我相信,如果我理解正確的話,您正在尋找類似以下內容的內容。
foreach像這樣改變你:
foreach($dates as $date) {
echo "<li><h1>{$date}</h1></li>" ."\n";
$expression = "//event/startdate[.='{$date}']";
$events = $sxml->xpath($expression) ;
foreach ($events as $event){
echo $event->xpath('.//following-sibling::description')[0]."\n";
if (($event->xpath('.//following-sibling::alldayevent'))[0] == "true") {
echo "\t" , "<li><div class='time'>All Day</div></li>" ."\n";
} else {
$st = $event->xpath('.//following-sibling::starttime')[0];
$et = $event->xpath('.//following-sibling::endtime')[0];
echo "\t" , "<li><div class='starttime'>$st</div></li>" ."\n";
echo "\t" , "<li><div class='endtime'>$et</div></li>" ."\n";
}
}
}
輸出:
<li><h1>24/11/2021</h1></li>
Event 1
<li><div class='time'>All Day</div></li>
Event 2
<li><div class='starttime'>14:00</div></li>
<li><div class='endtime'>16:30</div></li>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/368130.html
上一篇:使用xslt3.0回圈查找
