Home > Enterprise >  PHP SimpleXML error caused by missing times
PHP SimpleXML error caused by missing times

Time:11-26

I have the below code, which is displaying a calendar XML feed, however, not all events have a start/end time. This causes an error. I'd like for when an event does not have a start and end time, for it to display 'All Day' instead.

//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>";

Sample XML file below:

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

Expected Output:

If the event has a time/alldayevent = true then show start and end time, else if alldayevent = true, output 'All Day'

CodePudding user response:

I believe, if I understand you correctly, you are looking for something like the following.

Change your foreach like this:

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";
        
}
          }
}

Output:

<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>
  • Related