0

I am using a parser to change certain span elements to corresponding heading elements. I have the following code:

$headingReplace[1]['h']     = 'h1';
$headingReplace[1]['string']    = '/html/body//span[@class="heading1"]';            $headingReplace[1]['h']     = 'h1';

    foreach($headingReplace as $heading){
        foreach ($xp->query($heading['string']) as $span) {
            $h1 = $dom->createElement($heading['h']);
            $h1->setAttribute('class', $span->getAttribute('class'));
            while($span->childNodes->length > 0) {
                $h1->appendChild($span->childNodes->item(0));
            }
            $span->parentNode->replaceChild($h1, $span);
        }   
    }
    return $dom->saveHtml();

It all works fine, but the spans are also wrapped in p tags, eg.

<p><span class="heading1">Blah Blah</span></p>

Which I want removed. I guess after the 'appendChild' line, I want a line to 'removeParent', but I can't get it to work. Any ideas?

Thanks in advance.

hakre
  • 193,403
  • 52
  • 435
  • 836
Inigo
  • 8,110
  • 18
  • 62
  • 110
  • Shouldn't $span->parentNode->parentNode->replaceChild($h1, $span->parentNode); do what you want? – Pelshoff Dec 30 '11 at 21:59
  • Ah, thanks, Pelshoff! Duh! I was looking for some sort of 'removeParent' command. I'd like to ask one more question though, as a new problem has now presented itself. If I wanted to insert a '
    after every heading, how would I do it...? Thanks
    – Inigo Dec 30 '11 at 22:20

1 Answers1

0

Shouldn't $span->parentNode->parentNode->replaceChild($h1, $span->parentNode); do what you want?

In order to add a node after a given node, you can use something like (untested!):

if ($h1->nextSibling) {
    $h1->parentNode->insertBefore($h1->nextSibling, $dom->createElement('br'));
} else {
    $h1->parentNode->appendChild($dom->createElement('br'));
}
Pelshoff
  • 1,464
  • 10
  • 13
  • Spot on, Pelshoff, thanks for your help. – Inigo Dec 30 '11 at 23:43
  • You don't need to check `nextSibling` for `insertBefore` - if it is `NULL` then `insertBefore` appends. If not, it inserts before. No if required. – hakre Jun 23 '13 at 22:29