Simple Dom Parser在表中获得跨度值

时间:2012-09-04 00:21:00

标签: php simpledom

我正在使用Simple DOM Parser,我试图从动态表中获取一些信息,如下所示:

<table />
<tr>
   <td class="histogram-msg top-row">5 star</td>
   <td class="top-row bar-cell"><span class="bar bar5" style="width:150px">&nbsp;</span>&nbsp;<span>55</span></td>
</tr>
<tr>
   <td class="middle-row histogram-msg">4 star</td>
   <td class="middle-row bar-cell"><span class="bar bar4" style="width:65px">&nbsp;</span>&nbsp;<span>24</span></td>
</tr>
<tr>
   <td class="middle-row histogram-msg">3 star</td>
   <td class="middle-row bar-cell"><span class="bar bar3" style="width:38px">&nbsp;</span>&nbsp;<span>14</span></td>
</tr>
<tr>
   <td class="middle-row histogram-msg">2 star</td>
   <td class="middle-row bar-cell"><span class="bar bar2" style="width:19px">&nbsp;</span>&nbsp;<span>7</span></td>
</tr>
<tr>
   <td class="bottom-row histogram-msg">1 star</td>
   <td class="bottom-row bar-cell"><span class="bar bar1" style="width:35px">&nbsp;</span>&nbsp;<span>13</span></td>
</tr>
</table>

我正在尝试抓住表中的值,即:5星| 55,4星| 24等。

我通过$ret = $html->find('.user-ratings');获取此信息,当我尝试打印span标签时,它只给我一堆空白区域。

如何从上表中获取评级类型和值?

1 个答案:

答案 0 :(得分:1)

这将做你想做的事情:

<?php

include('simple_html_dom.php');

$f = file_get_html('s.html');

foreach($f->find('td[class=histogram-msg]') as $n) {

foreach($n->parent()->find('td[class=bar-cell]') as $p) {
    $ratings[] = array('stars' => $n->innertext, 
   'rating' => strip_tags(str_replace("&nbsp;", "", $p)));
    }
}

print_r($ratings);

Array
(
[0] => Array
    (
        [stars] => 5 star
        [rating] => 55
    )

[1] => Array
    (
        [stars] => 4 star
        [rating] => 24
    )

[2] => Array
    (
        [stars] => 3 star
        [rating] => 14
    )

[3] => Array
    (
        [stars] => 2 star
        [rating] => 7
    )

[4] => Array
    (
        [stars] => 1 star
        [rating] => 13
    )

)