Leo Loki Leo Loki - 1 year ago 66
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;

$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
, but how get style

Answer Source

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


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


$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