Append child/element in head using XML Manipulation

我们两清 提交于 2019-12-11 22:25:18

问题


I would like to replace <includes module="styles" /> with the $styles string at the position where it is. Unfortunately it appends it in the body and not in the head. Anyway, maybe there is another way to realize this issue?

$xml = <<<EOD
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <includes module="styles" />
</head>
<body>
    <includes module="m1" />
    <includes module="m2" />
</body>
</html>
EOD;


$styles = <<<EOD
<styles>
    .m1{
        font-size: 12px;
        font-family: Helvetica, Arial, sans-serif;
        color: blue;
    }
</styles>
EOD;


$dom = new DOMDocument();
$dom->loadXML($xml);

$elements = $dom->getElementsByTagName('includes');
for ($i = $elements->length-1; $i >= 0; $i--) { 
    $element = $elements->item($i);

    $newNode = $dom->createDocumentFragment();
    $mod = $element->getAttribute('module');
    if($mod==='styles'): $newNode->appendXML($styles); endif;
    $element->parentNode->replaceChild($newNode, $element);
}

print $dom->saveXml($dom->documentElement);

cheers


回答1:


You need to put the $element->parentNode->replaceChild($newNode, $element); inside your IF clause.
I also recommend to use foreach and bracket (makes it more readable)

foreach ($dom->getElementsByTagName('includes') as $element) { 
   $mod = $element->getAttribute('module');
   if($mod === 'styles') {
      $newNode = $dom->createDocumentFragment();
      $newNode->appendXML($styles);
      $element->parentNode->replaceChild($newNode, $element);
   }
}



回答2:


I found the bug, and it's pretty embarrassing! I misspelled <styles>. its supposed to be <style>! Obviously it automatically moves custom tags into the body.

@Javad That's funny. Because the php tester leaves the wrong styles tag in the head, but not on my xampp. Maybe because it has something to do with the php version?



来源:https://stackoverflow.com/questions/23817565/append-child-element-in-head-using-xml-manipulation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!