jlee jlee - 4 days ago 6
PHP Question

Remove table inline style using PHP

Is there an easy way to remove inline styles and attributes from a table using PHP.

For example, remove class, style, width, height from code below:

<tr class=xl96 height=30 style='mso-height-source:userset;height:23.1pt'>
<td height=30 class=xl99 style='height:23.1pt;border-top:none'>9</td>
<td class=xl100 style='border-top:none;border-left:none'>46333</td>
<td class=xl101 style='border-top:none;border-left:none'>&yen;698</td>
<td class=xl99 style='border-top:none;border-left:none'>48</td>
<td class=xl100 style='border-top:none;border-left:none'>2077988</td>
<td class=xl101 style='border-top:none;border-left:none'>&yen;698</td>
<td class=xl98></td>
<td class=xl96></td>
<td class=xl96></td>
</tr>


Expected Result:

<tr>
<td>9</td>
<td>46333</td>
<td>&yen;698</td>
<td>48</td>
<td>2077988</td>
<td>&yen;698</td>
<td></td>
<td></td>
<td></td>
</tr>

Answer
$doc = new DOMDocument(); 
$doc->loadHTML($html); 

foreach($doc->getElementsByTagName('*') as $node) 
{ 
    $node->removeAttribute('height'); 
    $node->removeAttribute('style'); 
    $node->removeAttribute('class');
} 

$doc->removeChild($doc->firstChild);
$doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild);

echo $doc->saveHTML(); 

Output

<tr><td>9</td> <td>46333</td> <td>&yen;698</td> <td>48</td> <td>2077988</td> 
<td>&yen;698</td> <td></td> <td></td> <td></td> </tr> 
Comments