【问题标题】:remove inline style properties and add html attributes using php删除内联样式属性并使用 php 添加 html 属性
【发布时间】:2011-05-17 10:39:46
【问题描述】:

1) 转换

<table style="width: 700px; height: 300px; background-color: #ff0000;" border="0">

到

<table width="700" height="300" bgcolor="#ff0000" border="0">

2) 转换

<table style="width: 700px; background-color: #ff0000;" border="0">

到

<table width="700" bgcolor="#ff0000" border="0">

我正在使用 Joomla 1.5.x,其中内容客户端可以添加表格或嵌套表格。 Tinymce 对表格尺寸、背景属性使用内联样式。但是当我们尝试从表格的前端内联样式生成 pdf 时,会被忽略。 Joomla 正在使用 TCPDF 生成我已经更新了版本但同样的问题。当我将 css 属性转换为 html 属性时,它会以格式化的方式生成表格。因此考虑将 table、td、th 的所有内联样式替换为 html 属性。尝试了该网站上的许多线程,但由于我不擅长正则表达式,因此无法使用它们。

请帮助我这样做。

提前致谢。

【问题讨论】:

    标签: php css attributes add


    【解决方案1】:

    我认为您可以为此使用 PHP DOM。

    1) 使用 DOMElement::getAttribute() 获取属性style=的值

    2) 使用$split = explode(";", $style) 分隔这些css 值

    3) 对于 $split 的每个条目 $i,$attributes = explode(":", $split[$i]),在获取属性的名称及其值。

    4) 现在 $attributes 包含两个值:属性和该属性的值。

    5) 使用 DOMElement::setAttribute() 添加 $attributes 的值。

    所以,把所有东西都写成代码:

    $dom = new DOMDocument();
    
    $dom->loadHTML($html);
    
    $atrvalue= $dom->getAttribute("style");
    
    $split = explode(";", $atrvalue);
    
    for ($i=0; $i<=count($split); $i++) {
        $attribute = explode(":", $split[$i]);
        $node = $doc->createElement("table");
        $newnode = $doc->appendChild($node);
        $newnode->setAttribute($attribute[0], $attribute[1]);
    }
    

    这种方式不涉及正则表达式 :) 但您需要修改它以适应您的上下文。

    【讨论】:

    • 乐:谢谢。但我的 $html 不仅有 table 标签,它是带有 p、div、span、b、table 标签的 html 内容。只有当我只有桌子时,你的回答才会有帮助。
    • 你的问题解决了吗?我认为你有什么标签并不重要,你可以把可能的标签放在数组中,比如 $arr = array('table', 'a', 'p', 'span') 并使用循环处理:)当你自己能找到的时候,我不能给你确切的答案:)
    猜你喜欢
    • 2011-02-08
    • 2013-02-02
    • 2014-05-31
    • 1970-01-01
    • 2021-04-22
    • 2013-11-25
    • 1970-01-01
    • 2015-12-13
    • 1970-01-01
    相关资源
    最近更新 更多