DOMDocument 解析 - 如何从 TD 获取样式背景色


$contents = '<table><tr><td style="background-color:#fffddd;">Row 1 Column 1</td><td style="background-color:#444;">Row 1 Column 2</td></tr><tr><td style="background-color:#555;">Row 2 Column 1</td><td style="background-color:#666;">Row 2 Column 2</td></tr></table>';
$DOM = new DOMDocument;
$DOM->loadHTML($contents);
$items = $DOM->getElementsByTagName('tr');
$str = "";
foreach ($items as $node) {
    foreach ($node->childNodes as $element) {
        $str .= $element->nodeValue . ", ";
    }
    $str .= "<br />";
}
echo $str;

它的代码以td返回文本,但是如何从td中获取样式background-color

我没有测试过它,但它应该是:

$element->getAttribute('style'); 

如果您的样式标签中有多个样式,则可以使用正则表达式。

更新:

$re = "/background-color:\s*(\#.*?);/"; 
$str = "background-color: #fffddd; color: #000; font-size: 14px;"; 
preg_match($re, $str, $matches);

$matches应包含背景色。但这也没有经过很好的测试。可能是您必须对极端情况进行一些调整 RegEx

您可以通过 ->getAttribute("style") 访问 style="" 属性。在您的foreach 中,您可以添加以下内容:

$str = array();
foreach ($items as $node) {
    foreach ($node->childNodes as $element) {
        $str[] = array($element->nodeValue . ", ", $element->getAttribute("style"));
    }
}

上面的代码将返回一个二维数组,其中包含值和样式:

echo $str[0][0]; // Row 1 Column 1,
echo $str[0][1]; // background-color:#fffddd;

但是,如果您的样式看起来像(例如):

style="background-color: #fffddd; color: #000; font-size: 14px;"

PHP 返回将为:

background-color: #fffddd; color: #000; font-size: 14px;

因此,如果您只需要背景色,则需要解析此style=""返回。

最新更新