根据类名解析HTML行的PHP代码

4

如何获取具有特定类名(例如)的所有行:

<tr class="dailyeventtext" bgcolor="#cfcfcf" valign="top">

然后将该行中的每个单元格放入数组中?

我使用了cURL从客户端服务器获取页面。


你能更好地定义“将该行中的每个单元格放入数组中”吗?DOM节点?文本内容?内部HTML? - alex
1个回答

7
$matches = array();

$dom = new DOMDocument;

$dom->loadHTML($html);

foreach($dom->getElementsByTagName('tr') as $tr) {
    if ( ! $tr->hasAttribute('class')) {
       continue;
    }

    $class = explode(' ', $tr->getAttribute('class'));

    if (in_array('dailyeventtext', $class)) {
       $matches[] = $tr->getElementsByTagName('td');
    }

}

谢谢Alex。现在我该如何获取每个单元格中的值?谢谢。 - Anderson
@Anderson:您是指将每个单元格的文本作为单独的数组元素吗?只需使用array_map()函数映射列,返回textContent属性即可。 - alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接