使用XML操纵将子元素附加在头部 [英] Append child/element in head using XML Manipulation

查看:75
本文介绍了使用XML操纵将子元素附加在头部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将< includes module = styles /> 替换为$ styles字符串。不幸的是,它附加在身体而不是头部。无论如何,也许还有另一种方法可以解决这个问题?

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

欢呼

推荐答案

我发现了这个错误,这很尴尬!我拼错了< styles> 。它应该是< style> !显然,它会自动将自定义标签移到正文中。

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真有趣。因为php测试人员在头部留下了错误的样式标签,但在我的xampp上却没有。也许是因为它与php版本有关?

@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?

这篇关于使用XML操纵将子元素附加在头部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆