bizzr3
bizzr3

Reputation: 1955

Domdocument AppendChid

I`m using this routine:

    $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();

to find all a tags in a html string such as this :

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

and wrap the a tags with an h4 tag. When I execute myscript the result was malformed and the output is:

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

but I want this format :

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

any suggestions please.

Upvotes: 1

Views: 231

Answers (1)

Guumaster
Guumaster

Reputation: 389

Have you tried to use replaceChild() ? Here, your code modified. Couldn't try it, but should work.

   $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();

Upvotes: 2

Related Questions