我想创建一组<style>
标记并将其添加到HTML文档的头标记中。
我知道我可以这样开始:
$url_contents = file_get_contents('http://example.com');
$dom = new DOMDocument;
$dom->loadHTML($url_contents);
$new_elm = $dom->createElement('style', 'css goes here');
$elm_type_attr = $dom->createAttribute('type');
$elm_type_attr->value = 'text/css';
$new_elm->appendChild($elm_type_attr);
现在,我也知道我可以向HTML添加新的样式标签,如下所示:
$dom->appendChild($ss_elm);
$dom->saveHTML();
然而,这将创建以下场景:
<html>
<!--Lots of HTML here-->
</html><style type="text/css">css goes here</style>
上述内容基本上毫无意义;CSS没有被解析,只是放在那里。
我在网上找到了这个解决方案(显然不起作用):
$head = $dom->getElementsByTagName('head');
$head->appendChild($new_elm);
$dom->saveHTML();
谢谢你的帮助!!
编辑:
有可能吗?
getElementsByTagName
返回一个节点数组,因此可能尝试
$head->[0]->appendChild($new_elm);
$head = $dom->getElementsByTagName('head');
返回DOMNodeList。我认为最好获得像这样的第一个元素
$head = $dom->getElementsByTagName('head')->item(0);
因此$head将是一个DOMNode对象。因此,您可以使用appendChild方法。
这是适用于我的解决方案
// Create new <style> tag containing given CSS
$new_elm = $dom->createElement('style', 'css goes here');
$new_elm->setAttribute('type', 'text/css');
// Inject the new <style> Tag in the document head
$head = $dom->getElementsByTagName('head')->item(0);
$head->appendChild($new_elm);
你也可以在末尾添加这一行,以获得一个干净的缩进
// Add a line break between </style> and </head> (optional)
$head->insertBefore($dom->createTextNode("'n"));