【问题标题】:using PHP simple html dom get attributes name in span?使用 PHP 简单的 html dom 在 span 中获取属性名称?
【发布时间】:2014-06-01 04:23:16
【问题描述】:

如果“标签”是正确的术语,我不是,但我必须从这个跨度中获取“数据时间”值到一个数组中。如何使用简单的 html dom 来获取它们?

这是我试图摆脱“数据时间”的跨度。

include('../simpleHtmlDom/simple_html_dom.php');

// Put the Twitters username here
$user = "yadayada";

$html = file_get_html("https://twitter.com/$user");
$ret = $html->find('div[class=ProfileTweet-contents]'); 
$ret = $html->find('p[class=ProfileTweet-text js-tweet-text u-dir]'); 

/// tries to get the time code but does only gets the span
$date = $html->find('span[class=js-short-timestamp js-relative-timestamp]', 0);

$DoesNotWork = $html->find( "data-time", 0 );


echo $ret[1]; // get's a users tweet. 

echo $DoesNotWork; 

日期的结果

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

我认为它是这样的,但这段代码不起作用。 $html->find("数据时间", 0);

【问题讨论】:

标签: html simple-html-dom


【解决方案1】:

你可以试试这个:

// Include the script
$url = 'https://twitter.com/yourusername';
$html = file_get_html($url);
$dateTimes = array();
foreach ($html->find('div.GridTimeline .js-short-timestamp') as $value) {
    $dateTimes[] = $value->innertext;
}

print_r($dateTimes);的结果:

Array
(
    [0] =>      2h   
    [1] =>      2h   
    [2] =>      2h   
    // Truncated...
    [10] =>      11h   
    [11] =>      May 30   
    [12] =>      May 30   
    [13] =>      May 6   
    // Truncated...
)

【讨论】:

    【解决方案2】:

    我能够使用此代码获取日期,但我认为有更好的方法。我认为最好找到一个简单的 dom 代码来获取行内日期时间的文本

    <span class"js-short-timestamp js-relative-timestamp" date-time="89393748474">
    

    但是我使用了两个“列表”php 行,如下所示,并且有效。

    $dateTimes = array();
    foreach ($html->find('div.GridTimeline .js-short-timestamp') as $value) {
        $dateTimes[] = $value->outertext;
    }
    //  These are the lines I get the date-time from.
    list($Gone,$Keep) = explode("data-time=\"", $dateTimes[0]);
    list($Date,$Gone) = explode("\"", $Keep);
    
    $Date =  date('M d, Y', $Date);
    

    【讨论】:

      【解决方案3】:

      你想使用:

      $html->find( "[data-time]", 0 );
      

      【讨论】:

        【解决方案4】:

        如果有人在 2021 年登陆这里,并且没有 1 个谷歌搜索结果:

        除非我误解了您的意图,否则您可能会使用(使用 simplehtmldom)实现您想要的:

        $html->find('span[data-time]')->attr[data-time];
        

        官方的 simplehtmldom 文档没有提到这一点。但是,https://stackoverflow.com/a/14456823/10050838 是一种可能的来源。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-08-27
          • 2012-04-06
          • 1970-01-01
          • 2019-01-20
          • 1970-01-01
          • 2013-01-05
          • 2013-01-14
          相关资源
          最近更新 更多