Php strotime未插入数据库
所以我在抓取一个网站上的数据,我抓取的一个数据是某些项目的日期 项目日期格式为“2015年3月11日星期三” 我一直在尝试将它插入我的mysql数据库。数据库的结构包含一列,其中“datapublished”作为时间戳Php strotime未插入数据库,php,mysql,web-scraping,strtotime,Php,Mysql,Web Scraping,Strtotime,所以我在抓取一个网站上的数据,我抓取的一个数据是某些项目的日期 项目日期格式为“2015年3月11日星期三” 我一直在尝试将它插入我的mysql数据库。数据库的结构包含一列,其中“datapublished”作为时间戳 `feeddatapublished` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) 当使用数据更新其余列时,它会使用以下代码进行良好更新 $stmt = $dbh->p
`feeddatapublished` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)
当使用数据更新其余列时,它会使用以下代码进行良好更新
$stmt = $dbh->prepare("INSERT INTO `feedsdata` (`id`, `feedid`, `feedurl`, `feedsummary`, `feedtitle`, `feeddatapublished`) VALUES (NULL, :feed_id, :feed_url, :feed_summary, :title, :datapublished)");
$stmt->bindParam(':feed_id', $feed_id);
$stmt->bindParam(':feed_url', $feed_url);
$stmt->bindParam(':feed_summary', $feed_summary);
$stmt->bindParam(':title', $feed_title);
$stmt->bindParam(':datapublished',$datepublished);
$stmt->execute();
在传递要插入的字符串之前,我转换了提要中的字符串
$datepublished = strtotime(scrape_between($separate_result, "<span class=\"date\">", "</span>"));
$datepublished=strotime(在($separate_result,“,”)之间进行刮取);
scrape_between是我用于刮片的一个函数
当回显$datepublished时,我得到了时间戳1458155700,从我看到的时间戳不正确
所有其他列都将根据需要进行更新,唯一不更新的列是datepublished列
我的两个问题是
MySQL的
timestamp
格式是2016-02-13 15:48:29
或Y-m-d H:i:s
首先将您的unix时间戳
转换为该格式,然后MySQL将接受它
或者
<?php
$datapublished = date("Y-m-d H:i:s", strtotime(scrape_between($separate_result, "<span class=\"date\">", "</span>")));
如果您知道正在抓取的网页上使用的日期格式,并且该格式保持不变,则可以使用该格式进行更安全、更受控的日期解析
<?php
$datestring = "Wed 11th March, 2015";
$date = DateTime::createFromFormat("D dS F, Y", $datestring);
// Reset hours, minutes and seconds - otherwise the current time is used
$date->setTime(0, 0, 0);
// Format for MySQL database insertion
$datepublished = $date->format("Y-m-d H:i:s");
问题在于strotime
不够聪明,无法识别字符串,因此其最佳猜测是1458155700
您可以添加其他步骤来清除日期:
$scrape = scrape_between(...);
$cleanDate = preg_replace(
'/[a-z]+ ([0-9]{1,2})[a-z]+ ([a-z]+), ([0-9]{4})/i',
'$1 $2 $3',
$scrape
);
$datepublished = strtotime($cleanDate);
preg\u replace
函数使用正则表达式删除不必要的部分。是否确定scrape\u between()
函数工作正常并给出正确的结果?此外,您是否收到任何php和/或MySQL错误。您的代码是否已打开错误报告?它正在为我提供正确的结果。我回显并检查了它们,这是转换成时间戳的过程,但不起作用。错误报告(E_全部);ini设置(“显示错误”,1);设置好了,什么都没有通过这是否是问题:?我已经设置了区域设置,但是我在php中重置了它以进行检查。一个例子是。。。2015年11月24日星期二,Strotime发布了1480450500条消息,这可能是因为删除的数据中有空格吗?非常有用,谢谢!我没意识到mysql有不同的格式!不用担心,如果能帮助你,请考虑接受答案。欢迎来到SO!
$scrape = scrape_between(...);
$cleanDate = preg_replace(
'/[a-z]+ ([0-9]{1,2})[a-z]+ ([a-z]+), ([0-9]{4})/i',
'$1 $2 $3',
$scrape
);
$datepublished = strtotime($cleanDate);