Filtering XML file, with PHP

前端 未结 2 486
一整个雨季
一整个雨季 2021-01-16 01:53

I want to load XML file and then remove all where is bigger/older then 7 years. Date format is YYYY-MM-DD.

2条回答
  •  鱼传尺愫
    2021-01-16 02:05

    You can either use SimpleXML, DOM or XSL for it.

    Example XML (shortened for brevity (from Revision 1 of your question)):

    $xml = <<< XML
    
        
            1995-12-21
        
        
            2010-12-21
        
    
    XML;
    

    With SimpleXml

    $sevenYearsAgo = new DateTime('-7 years');
    $CriminalCase  = new SimpleXmlElement($xml);
    for ($i = 0; $i < $CriminalCase->Charge->count(); $i++) {
        $dispositionDate = new DateTime($CriminalCase->Charge->DispositionDate);
        if ($dispositionDate < $sevenYearsAgo) {
            unset($CriminalCase->Charge[$i]);
        }
    }
    echo $CriminalCase->asXml();
    

    With DOM

    $dom = new DOMDocument;
    $dom->loadXml($xml);
    $xpath = new DOMXPath($dom);
    $oldCases = $xpath->query(
        sprintf(
            '//Charge[substring-before(DispositionDate, "-") < %d]',
            date('Y', strtotime('-7 years'))
        )
    );
    foreach ($oldCases as $oldCase) {
        $oldCase->parentNode->removeChild($oldCase);
    }
    echo $dom->saveXml();
    

    With XSLT

    
    
    
      
      
        
          
              
      
      
        
          
        
         
    
    

    and then use this PHP Code to transform it

    $doc = new DOMDocument();
    $xsl = new XSLTProcessor();
    $doc->loadXml($xsl);
    $xsl->importStyleSheet($doc);
    $doc->loadXml($xml);
    echo $xsl->transformToXML($doc);
    

提交回复
热议问题