html简单的dom得到日期 - 时间vaule

时间:2015-06-03 04:57:48

标签: html twitter simple-html-dom

我想在这个html中获取日期时间的时间戳。

<span class="js-short-timestamp js-relative-timestamp"
    data-time="1401528672"
    data-long-form="true">
    15h
  </span>

使用 html simple dom 如何从此html获取值“1401528672”。是的,值/时间戳会改变,所以我需要在html中获得[date-time]的值。

有什么想法吗?

include('simpleHtmlDom/simple_html_dom.php');

$html = file_get_html("https://twitter.com/$user");
//not working
$date = $html->find('span[data-time]->attribute()', 0);
print_r($date);
exit;

2 个答案:

答案 0 :(得分:2)

请尝试以下代码:

include('simpleHtmlDom/simple_html_dom.php');

$html = str_get_html('<span class="js-short-timestamp js-relative-timestamp"
    data-time="1401528672"
    data-long-form="true">
    15h
  </span>');
$data = $html->find('span', 0);

echo $data->attr['data-time'];

@Papa De Beau:我使用simplehtmldom尝试了上面的代码并且它有效:)

答案 1 :(得分:1)

使用普通Html的解决方案,

// Create a DOM object from a string
$html = str_get_html('<span class="js-short-timestamp js-relative-timestamp"
    data-time="1401528672"
    data-long-form="true">
    15h
  </span>');

//Now get the reference to Span object
$data = $html->find('span', 0);

//Now get the attribute value 
echo $data->attr['data-time'];

如果您可以选择使用JavaScript并且可以访问span元素源代码,则可以使用以下解决方案

如果你给span元素一些id属性,比如span1,你可以使用getAttribute()方法获取你想要的信息..见下面的代码

<span class="js-short-timestamp js-relative-timestamp" id='span1'
    data-time="1401528672"
    data-long-form="true">
    15h
</span>

<!-- now retrieve the value of date-time any where else -->

var element = document.getElementById('span1');
var dateTimeVal = element.getAttribute("data-time");

希望它有效..

See full example here