Leo Loki Leo Loki - 5 months ago 31
PHP Question

DOMDocument parse - How get style background-color from 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;


It code return text in
td
, but how get style
background-color
from
td
?

Answer

I've not tested it, but it should be:

$element->getAttribute('style'); 

If there are multiple styles in your style tag you can use a regex.

Update:

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

$matches should contain the background color. But this is also not well tested. Could be that you have to tweak the RegEx a little bit for corner cases