首页 > 解决方案 > 搜索匹配特定日期的 xml 数据

问题描述

想知道是否有人可以帮助我。我有一个 xml 文件,其中包含日期格式为 2020-12-06T01:00:02.578+11:00 的日志。

我想使用 xpath 来搜索数据并过滤两个日期之间的记录。我无法弄清楚如何通过 xpath 过滤器搜索本身来做到这一点。

到目前为止,下面是我的代码,搜索过滤器不起作用的原因很明显,因为它是一个文本值。我需要先隐瞒这个日期吗?

下面使用大于号的匹配日期代码不起作用。

**Sample XML:**
<data>
<faultRecord ack="no"
     cause="config-error"                
     Action="deletePresent"
     code="3564"
     created="2020-12-06T01:00:02.578+11:00"/>
</data>


$xml = simplexml_load_file('faults.xml');

$faults = new SimpleXMLElement('faults.xml',null,true);
  
foreach($faults->xpath('//data/faultRecord[@created > "2020-12-06"]') as $faultRecord) {        

    foreach($faultRecord->attributes() as $Attribute => $value)     
            
            if ($Attribute == 'created' or  $Attribute == 'description') {
                echo "{$Attribute} = {$value} <br /> <br /> ";                  
            }           
}         

谢谢

编辑 想出了一​​种方法来做到这一点,以防万一它对任何人有帮助:

    $faults = new SimpleXMLElement('faults.xml',null,true);
  
foreach($faults->xpath('//data/faultRecord[@code = "3564"]') as $faultRecord) {     
    
    $date = strtotime($faultRecord->attributes()->created); 
    
    if ($date > 1607176802) {
    foreach($faultRecord->attributes() as $Attribute => $value)                     
                        
        if ($Attribute == 'created' or  $Attribute == 'description') {
            echo "{$Attribute} = {$value} <br /> <br /> ";                  
        }           
        
    }
}

标签: phpxml

解决方案


也许这可以帮助你。 XPath 查询按日期过滤

也许,要获得更多帮助,您需要构建 XML 结构。


推荐阅读