سؤال

In the XML file, the date format is being received as: 20140327163000 (YYYYMMDDHHMINSEC). I need to parse the date and convert it into the following format (DD/MM/YYYY HH:MIN:SS) before posting it into the database. The following is the code I am using, however it is not posting anything in the database:

<?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/*");

?>
هل كانت مفيدة؟

المحلول

Try this piece and see if it works for you:

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

EDIT:

So, instead of the value 20140327163000 use a variable that holds the value you want to save (and don't use var_dump of course) - this was just to present that this piece of code would parse the value given to the string formatted as you want.

$date = new DateTime($yourValue);
$dateToSave = $date->format('d/m/Y H:i:s');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top