将XML日期提取到PHP

时间:2015-06-16 17:32:26

标签: php xml date

我有一个XML文档,其条目如下所示:

<recall-number id="F-2402-2015">
     <product-type>Food</product-type>
     <event-id>70195</event-id>
     <status>Ongoing</status>
     <recalling-firm>Northhampton Peanut Company</recalling-firm>  
     <city>Severn</city>
     <state>NC</state>
     <country>US</country>
     <voluntary-mandated>Voluntary: Firm Initiated</voluntary-mandated>
     <initial-firm-notification>Letter</initial-firm-notification>
     <distribution-pattern>CT, MA, NJ, NY and PA.</distribution-pattern>
     <classification>Class II</classification>  
     <product-quantity>unknown</product-quantity> 
     <reason-for-recall>Undeclared Non-Allergen: Sulfites</reason-for-recall> 
     <recall-initiation-date>12/24/2014</recall-initiation-date>
     <report-date>06/10/2015</report-date>
</recall-number>

我正在使用simplexml_load_file并且能够获取所有字段,但最后的两个日期字段(recall-initiation-date / report-date)显示为空白。经过一些研究,我使用了日期函数:

function get_recalls() {
     $url = "Enforcement-Reports-Export.xml";
     $xml = simplexml_load_file($url);
     foreach($xml->{'recall-number'} as $product) {
          $recall_initiation_date = date('d/m/Y', $product{'recall-initiation-date'});
          $report_date = date('d/m/Y', $product{'report-date'});

          echo $recall_initiation_date;
          echo $report_date;
     }
}

但是,它返回的日期是01/01/1970,而不是正确的日期。

1 个答案:

答案 0 :(得分:2)

因为date()期望将Unix时间戳作为参数,并且您给它一个字符串。使用strtotime()将这些日期转换为Unix时间戳。

$recall_initiation_date = date('d/m/Y', strtotime($product{'recall-initiation-date'}));
$report_date = date('d/m/Y', strtotime($product{'report-date'}));