【问题标题】:PHP SimpleXML error caused by missing times缺少时间导致的 PHP SimpleXML 错误
【发布时间】:2022-01-03 06:39:22
【问题描述】:

我有以下代码,它显示日历 XML 提要,但是,并非所有事件都有开始/结束时间。这会导致错误。我希望当一个事件没有开始和结束时间时,它会显示“全天”。

//load xml file
$sxml = simplexml_load_file($url) or die("Error: Cannot create object");

echo '<div class="calendar">';

#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>

预期输出:

如果事件有时间/alldayevent = true,则显示开始和结束时间,否则如果 alldayevent = true,则输出 'All Day'

【问题讨论】:

  • 请编辑您的问题并添加一个有代表性的 xml 示例,其中包含和不包含开始/结束时间以及每种情况下的预期输出。
  • 谢谢,问题已更新。

标签: php xml


【解决方案1】:

我相信,如果我对您的理解正确,您正在寻找类似以下的内容。

像这样更改您的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>

【讨论】:

    猜你喜欢
    • 2012-09-08
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2022-11-04
    • 2018-03-04
    • 2016-08-27
    • 2012-02-04
    相关资源
    最近更新 更多