我有以下脚本显示来自xml的数据。
events.xml
<SchoolCalendar>
<CalendarEvent>
<StartTime>07:30</StartTime>
<Title>test Title 1</Title>
<Location>Room 1</Location>
</CalendarEvent>
<CalendarEvent>
<StartTime>01:10</StartTime>
<Title>test Title 2</Title>
<Location>Room 15</Location>
</CalendarEvent>
<CalendarEvent>
<StartTime>03:30</StartTime>
<Title>test Title 3</Title>
<Location>Room 18</Location>
</CalendarEvent>
<CalendarEvent>
<StartTime>14:30</StartTime>
<Title>test Title 4</Title>
<Location>Room 21</Location>
</CalendarEvent>
<CalendarEvent>
<StartTime>14:30</StartTime>
<Title>test Title 5</Title>
<Location>Room 12</Location>
</CalendarEvent>
<CalendarEvent>
<StartTime>15:30</StartTime>
<Title>test Title 6</Title>
<Location>Room 111</Location>
</CalendarEvent>
php代码:
$today = date("H:i");
$lib = simplexml_load_file("events.xml");
$query = $lib->xpath("/SchoolCalendar/CalendarEvent[StartTime = '14:30']");
if( $query ) {
foreach($query as $node){
echo "<tr>";
echo "<td>$node->StartTime</td>";
echo "<td>$node->Title</td>";
echo "<td>$node->Location</td>";
echo "</tr>";
}
}
else {
}
使用上面的代码,它只显示StartTime为14:30的两个事件。如何显示所有未来事件,尝试跟随但没有显示任何内容。
$query = $lib->xpath("/SchoolCalendar/CalendarEvent[StartTime >= '$today']");
非常感谢任何帮助,谢谢。
除了迭代所有事件并检查它的StartTime
理论上有一个XPath解决方案使用>=
operator与xs:time
类型,如下所示:
/SchoolCalendar/CalendarEvent[xs:time(concat(StartTime, ':00')) >= xs:time('14:00:00')]
但是,这需要XPath 2+,而使用PHP,您只能访问XPath 1.0(带有一些XPath 2扩展)。尽管如此,它可以使用PHP 5的DOMXPath::registerPhpFunctions
在XPath中完成。
示例代码:
$doc = new DOMDocument;
$doc->loadXML($xml); //from string
$xpath = new DOMXPath($doc);
// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");
// Register PHP functions (time_greater_thanonly)
$xpath->registerPHPFunctions("time_greater_than");
function time_greater_than($nodes)
{
// Return true if time is greater or equal than now
return strtotime($nodes[0]->nodeValue) >= strtotime(date("H:i"));
}
// Call custom function on the CalendarEvent nodes instead of XQuery 2+ functions
$query = $xpath->query('/SchoolCalendar/CalendarEvent[php:function("time_greater_than", StartTime)]');
if ($query) {
foreach ($query as $node) {
echo "<tr>";
$values = explode("\n", trim($node->nodeValue));
foreach ($values as $str)
echo "<td>$str</td>";
echo "</tr>";
}
}
PS:要访问time_greater_than
的输出,我只需使用explode()
从当前节点的文本内容中获取值。要深入挖掘foreach
循环中的节点,请使用xquery,将当前$node
作为contextnode param:
$xpath->query(".//Location", $node)[0]->nodeValue
EG
if ($query) {
foreach ($query as $node) {
echo "<tr>";
echo "<td>".$xpath->query('.//StartTime', $node)[0]->nodeValue."</td>";
echo "<td>".$xpath->query('.//Title', $node)[0]->nodeValue."</td>";
echo "<td>".$xpath->query('.//Location', $node)[0]->nodeValue."</td>";
echo "</tr>";
}
}
PPS:从来没有XQuery版本也有fn:current-time()
。我不得不使用固定的xs:time
来使它工作。