Skip to content
Advertisement

PHP showing XML calendar data – merge day events

I have the following XML file, which I can’t edit.

<event>
<id>100</id>
<startdate>24/11/2021</startdate>
<description>Event Test 1</description>
</event>
<event>
<id>101</id>
<startdate>24/11/2021</startdate>
<description>Event Test 2</description>
</event>

I am then outputting this using simplexml_load_file($url) into a PHP file:

  $sxml = simplexml_load_file($url) or die("Error: Cannot create object");
foreach ($sxml->children() as $data)
{
echo "<li><h1>", $data->startdate . "</h1></li>";
echo "<li><h1>", $data->description . "</h1></li>";
}

This gives me an output as follows:

24/11/2021
Event Test 1
24/11/2021
Event Test 2

However, I would like to merge events by date, so the output would be as follows:

24/11/2021
    Event Test 1
    Event Test 2

How can I achieve this without editing the XML file?

Thanks!

Advertisement

Answer

Since you are dealing with with xml, you are probably better off selecting your data using xpath.

To demonstrate, assume your xml looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<doc>    
   <event>
      <id>100</id>
      <startdate>24/11/2021</startdate>
      <description>Event Test 1</description>
   </event>
  <event>
     <event>
      <id>101</id>
      <startdate>24/11/2021</startdate>
      <description>Event Test 2</description>
   </event>
      <id>102</id>
      <startdate>24/12/2021</startdate>
      <description>Event Test 3</description>
   </event>
       <event>
      <id>103</id>
      <startdate>24/12/2021</startdate>
      <description>Event Test 4</description>
   </event>    
</doc>

Then in your code:

#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 desription
   foreach ($events as $event){
       echo "t" , "<li><h1> {$event->xpath('./following-sibling::description')[0]}</h1></li>";
       echo "n";
   }
   echo "n";
}

Output:

<li><h1>24/11/2021</h1></li>
    <li><h1> Event Test 1</h1></li>
    <li><h1> Event Test 2</h1></li>

<li><h1>24/12/2021</h1></li>
    <li><h1> Event Test 3</h1></li>
    <li><h1> Event Test 4</h1></li>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement