Below is a simple example I've come up with which uses XPath to return all matching Event
elements and outputs the data as an HTML table (view output here) and uses the attribute names as column headings. I added in an extra Event
element to demonstrate iterating over multiple elements (and wrapped the Event
elements within an Events
element as valid XML documents must have a single root element).
<?php
function FormatData($data, $linkText = 'Link') {
if (substr($data, 0, 4) === 'http') {
if ($linkText === '') $linkText = $data;
return sprintf('<a href="%s">%s</a>', $data, $linkText);
} else {
return $data;
}
}
$xmlData = simplexml_load_string('<Events><Event Name="Last Reef" VenueName="Theater" EventDate="2014-03-21 15:00:00" DirectLink="https://tickets.ctsciencecenter.org/Public/loader.asp?target=hall.asp?event=45259"/><Event Name="Hidden Universe" VenueName="Theater" EventDate="2014-03-22 13:00:00" DirectLink="https://tickets.ctsciencecenter.org/Public/loader.asp?target=hall.asp?event=45695"/></Events>');
// do a global search to retrieve all "Event" elements
$events = $xmlData->xpath('//Event');
if (count($events) > 0) {
// get attribute names of first "Event" element
foreach($events[0]->attributes() as $attribute) {
$attributeNames[] = $attribute->getName();
}
// output as table column headings
echo '<table border="1"><tr><th>' . implode('</th><th>', $attributeNames) . '</th></tr>';
// iterate through each "Event" element and access each attribute value
foreach($events as $event) {
echo '<tr>';
foreach($attributeNames as $attributeName) {
echo '<td>' . FormatData($event[$attributeName]) . '</td>';
}
echo '</tr>';
}
echo '</table>';
} else {
echo 'No matching elements found';
}
?>