使用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?

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