Wrap DOM Element In Another DOM Element In PHP
I originally asked a question along these lines using Regex but was recommended to use the PHP DOM library instead... which is superior, but I am still stuck. Basically, I want to
Solution 1:
Why bother with re-creating the node? Why not just replace the node? (If I understand what you're trying to do)...
if($spancount == 0){
$element = $doc->createElement('span');
$element->setAttribute('style','color:#ffffff;');
$tag->parentNode->replaceChild($element, $tag);
$element->apendChild($tag);
}
Edit Whoops, it looks like you're trying to wrap everything under $tag
in the span... Try this instead:
if($spancount == 0){
$element = $doc->createElement('span');
$element->setAttribute('style','color:#ffffff;');
foreach ($tag->childNodes as $child) {
$tag->removeChild($child);
$element->appendChild($child);
}
$tag->appendChild($child);
}
Edit2 Based on your results, it looks like that foreach is not completing because of the node removal... Try replacing the foreach with this:
while ($tag->childNodes->length > 0) {
$child = $tag->childNodes->item(0);
$tag->removeChild($child);
$element->appendChild($child);
}
Solution 2:
This is great information, and sorry to come so late into the party, but there's one error for me... at the end:
$tag->appendChild($child);
should be
$tag->appendChild($element);
That's the only way I could get this to work.
Post a Comment for "Wrap DOM Element In Another DOM Element In PHP"