Domdocument AppendChild

时间:2012-03-11 13:31:56

标签: php html formatting domdocument appendchild

我正在使用这个例程:

    $dom = new DomDocument();
    @$dom->loadHTML('<?xml encoding="UTF-8">' . $row['body']);
    $xpath = new DOMXPath($dom);
    $as = $dom->getElementsBytagName('a');
    //if anchor exists
    if($as->length)
    {
        foreach ($as as $a)
        {
            //get parrent af anchor 
            $a_parent = $a->parentNode;
            //create h4 element
            $h4 = $dom->createElement('h4');
            //append a to h4
            $h4->appendChild($a);
            //append h4 to anchor parent
            $a_parent->appendChild($h4);    
        }
        $body = $dom->saveHTML();

查找html字符串中的所有a标记,例如:

<p>Lorem Ipsum is simply dummy text of the printing and 
typesetting<a href="#">foo</a> industry.</p>

并使用a标记包装h4标记。当我执行myscript时,结果格式错误,输出为:

<p>Lorem Ipsum is simply dummy text of the printing and
typesetting industry.<h4><a href="#">foo</a></h4></p>

但我想要这种格式:

<p>Lorem Ipsum is simply dummy text of the printing
and typesetting<h4><a href="#">foo</a></h4> industry.</p>

请提出任何建议。

1 个答案:

答案 0 :(得分:2)

您是否尝试过使用replaceChild()?在这里,您的代码已修改。无法尝试,但应该工作。

   $dom = new DomDocument();
    @$dom->loadHTML('<?xml encoding="UTF-8">' . $row['body']);
    $xpath = new DOMXPath($dom);
    $as = $dom->getElementsBytagName('a');
    //if anchor exists
    if($as->length)
    {
        foreach ($as as $a)
        {
            //get parrent af anchor 
            $a_parent = $a->parentNode;
            //create h4 element
            $h4 = $dom->createElement('h4');
            //append a to h4
            $clone = $a->cloneNode();
            $h4->appendChild($clone);
            //append h4 to anchor parent
            $a_parent->replaceChild($h4, $a);
        }
        $body = $dom->saveHTML();