doulin6088 2014-04-24 11:11
浏览 38
已采纳

使用SimpleXML填充HTML文件

I have an array containing some content like this:

    $content = array(
        array(
            'classname' => 'nopadding',
            'idname'    => 'car-volvo',
            'title' => 'Volvo'
        ),
        array(
            'classname' => 'nomargin',
            'idname'    => 'car-porsche',
            'title' => 'Porsche'
        )
    );

and I have an HTML file, serving as a template containing this:

    <li data-tpl-classname="class" data-tpl-idname="id"><span data-tpl-title="innerHTML"></span></li>

Now I want to use the array together with the HTML file to produce this:

    <li class="nopadding" id="car-volvo"><span>Volvo</span></li>
    <li class="nopadding" id="car-volvo"><span>Volvo</span></li>

I'm looking to write a general function that takes HTML files like the one above, looks for data-tpl- attributes and fills with the content from the array.

How can I achieve this? Is SimpleXML the way to go?

  • 写回答

1条回答 默认 最新

  • duanquannan0593 2014-04-24 12:45
    关注

    I've tried wrapping this up as generalized as possible but there's no guarantee this would work for all your templates, I need to have a look at them to see their common pattern.

    You can try the code:

    populate_html($template,$content,'li','data-tpl-');
    
    function populate_html($template,$content,$tag_name,$attr_name){
        $dom = new DOMDocument;
        $dom->loadHTML($template);
        $i=0;
        $tag = $dom->getElementsByTagName($tag_name)->item(0);
        foreach($content as $k=>$v){
    
            $li = "<".$tag_name;
            foreach ($tag->attributes as $attr) {
                if(stripos($template,$attr_name)!==FALSE){
                    $attr_short = substr($attr->nodeName,strrpos($attr->nodeName,'-')+1,strlen($attr->nodeName));
                    $li .= ' '.$attr->nodeValue.'="'.$content[$i][$attr_short].'"';
                }
            }
            $li .= "><span>".$content[$i]['title']."</span></".$tag_name.">";
            $i++;
            echo $li;
        }
    }
    

    DOMDocument is a class that will breakdown your string containing HTML that you pass into its attributes and values so that you can parse through them.

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错