使用PHP从XML转换数据格式

时间:2014-03-27 16:41:55

标签: php simplexml

在XML文件中,日期格式收到:20140327163000(YYYYMMDDHHMINSEC)。我需要解析日期并将其转换为以下格式(DD / MM / YYYY HH:MIN:SS),然后再将其发布到数据库中。以下是我正在使用的代码,但它没有在数据库中发布任何内容:

<?php 

// Create connection
$con=mysqli_connect("localhost","test","test","epg");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$dir = "xml-files/";
if (is_dir($dir)) {
  if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
      if (($file !== '.') && ($file !== '..') ) {
    $doc = simplexml_load_file($dir . $file); 

foreach ( $doc->ScheduleData->ChannelPeriod as $channelPeriod )
{
   $channelId = $channelPeriod->ChannelId;

   foreach ( $channelPeriod->Event as $event )
   {
      $beginTime = $event['beginTime'];
      $duration = $event['duration'];
      $programName = $event->EpgProduction->EpgText->Name;
      $description = $event->EpgProduction->EpgText->Description;
      $EventId = $event->EventId;

         $format = 'd-m-Y H:i:s';
        $date = DateTime::createFromFormat($format, '$beginTime');

      $sql = "insert into `epg` (`EventId`,`ChannelId`, `BeginTime`,`Duration`, `ShortName`, `Description`) values ('$EventId','$channelId', '$date','$duration', '$programName', '$description')";

        if (mysqli_query($con,$sql))
      {
      echo "Database updated successfully<br />";
      }
    else
      {
      echo "Error creating database: " . mysqli_error($con)."<br />";
      }


                    }
                }
            }
        }
  closedir($dh);
    }
}

$sql_delete = "DELETE FROM `EPG` WHERE BeginTime < ";

function deleteFiles($dir) {
    $files = glob($dir);
    foreach($files as $file){ 
      if(is_file($file))
        unlink($file); 
    }
}

deleteFiles("xml-files/*");

?>

1 个答案:

答案 0 :(得分:1)

试试这件作品,看看它是否适合你:

$date = new DateTime(20140327163000);
var_dump($date->format('d/m/Y H:i:s'));

编辑:

因此,代替值20140327163000使用一个包含您想要保存的值的变量(当然不要使用var_dump) - 这只是为了表明这段代码将解析给定的值根据需要格式化的字符串。

$date = new DateTime($yourValue);
$dateToSave = $date->format('d/m/Y H:i:s');