【问题标题】:Bug with strtotime()strtotime() 的错误
【发布时间】:2013-03-03 18:58:09
【问题描述】:

Simple HTML DOM 库用于从网页中提取时间戳。然后使用strtotime 将提取的时间戳转换为 MySQL 时间戳。

问题:strtotime() 用于有效的时间戳时,NULL 被返回(参见2:)。但是,当第二个示例中没有使用 Simple HTML DOM 时,一切正常。

发生了什么,如何解决??

输出:

1:2013-03-03, 12:06PM
2:
3:1970-01-01 00:00:00

var_dump($time)

string(25) "2013-03-03, 12:06PM"

PHP

include_once(path('app') . 'libraries/simple_html_dom.php');

// Convert to HTML DOM object
$html = new simple_html_dom();
$html_raw = '<p class="postinginfo">Posted: <date>2013-03-03, 12:06PM EST</date></p>';
$html->load($html_raw);

// Extract timestamp
$time = $html->find('.postinginfo', 0);
$pattern = '/Posted: (.*?) (.).T/s';
$matches = '';
preg_match($pattern, $time, $matches);
$time = $matches[1];

echo '1:' . $time . '<br>';
echo '2:' . strtotime($time) . '<br>';
echo '3:' . date("Y-m-d H:i:s", strtotime($time));

第二个例子

PHP(工作,没有简单的 HTML DOM)

// Extract posting timestamp
$time = 'Posted: 2013-03-03, 12:06PM EST';
$pattern = '/Posted: (.*?) (.).T/s';
$matches = '';
preg_match($pattern, $time, $matches);
$time = $matches[1];

echo '1:' . $time . '<br>';
echo '2:' . strtotime($time) . '<br>';
echo '3:' . date("Y-m-d H:i:s", strtotime($time));

输出(正确)

1:2013-03-03, 12:06PM
2:1362312360
3:2013-03-03 12:06:00

var_dump($time)

string(19) "2013-03-03, 12:06PM"

【问题讨论】:

  • 能否添加simple_html_dom.php代码?
  • @MIIB 当然:pastebin.com/DxhmsRC1
  • 几乎没有相关的可能性,您是否 100%确定您的输入相同?
  • @WesleyMurch 是的,我将时间戳 2013-03-03, 12:06PM EST 从第一个示例复制到第二个示例
  • 使用 var_dump 而不是 echo 来检查隐藏字符

标签: php web-scraping screen-scraping


【解决方案1】:

根据您的var_dump(),您从HTML 代码中提取的$time 字符串长度为25 个字符。

看到的字符串"2013-03-03, 12:06PM"只有19个字符长。

那么,这 6 个额外的字符在哪里?嗯,很明显,真的:你要解析的字符串真的是"&lt;date&gt;2013-03-03, 12:06PM"。但是当您将其打印到 HTML 文档中时,&lt;date&gt; 会被浏览器解析为 HTML 标记。

要查看它,请使用浏览器中的“查看源代码”功能。或者,好多更好的是,在打印任何 不应该包含 HTML 代码的变量时使用 htmlspecialchars()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多