我想用php解析一个元文件并将数据存储到我的数据库中。在这种情况下,我想找到以开头的行#
并将日期安全地保存到mySQL数据库中:
18923081293801293.animal=cat
#Tue Jun 14 12:40:44 CEST 2015
18923081293801293.name=Fred
18923081293801293.age=24
到目前为止,这是我的代码。它正在解析animal
,name
并且age
。
$properties = array();
foreach ($linesArray AS $line) {
if (false !== ($pos = strpos($line, '='))) {
$prop=array();
$prop[trim(substr($line, 0, $pos))] = trim(substr($line, $pos + 1));
$lineContArray = explode("=", $line);
$identArray = explode(".", $lineContArray[0]);
$ident = $identArray[0];
$type = $identArray[1];
$value = $lineContArray[1];
$found = 0;
for ($i=0; $i<count($properties); $i++) {
if ($properties[$i]['number'] == $ident) {
$properties[$i][$type]= $value;
$found=1;
break;
}
}
if ($found == 0) {
if (!empty($type)) {
$properties[] = array('number' => $ident, $type => $value);
} else {
$properties[] = array($ident => $value); }
}
}
}
$sql = "INSERT INTO farm (animal,name,age) values(?,?,?) ";
$q = $pdo->prepare($sql);
foreach($properties as $row) {
$q->execute(array($row['animal'], $row['name'], $row['age']));
}
但是我不知道如何解析日期行并将其作为日期进入我的数据库(列类型:datetime)。
要从文件中获取日期,您需要#
在循环中一行的开头检查a :
foreach ($linesArray AS $line) {
// Check for # as first character (but only if there is a first character).
if (strlen($line) && $line[0] == '#') {
// Convert everything except the first character to a date.
$date = strtotime(substr($line, 1));
// Convert it back to a string in a format that MySQL likes.
$strDate = date("y-m-d H:i:s", $date);
}
// Here the rest of your old continues.
if (false !== ($pos = strpos($line, '='))) {
...
然后,您可以像插入其他值一样将其插入数据库中。由于我不了解所有代码,因此不确定它是否完全适合您的代码,但它至少应该为您提供一些提示。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句