简体   繁体   English

使用 PHP DOMDocument 添加样式标签到头部

[英]Adding style tags to head with PHP DOMDocument

I want to create and add a set of <style> tags to the head tags of an HTML document.我想创建一组<style>标签并将其添加到 HTML 文档的 head 标签中。

I know I can start out like this:我知道我可以这样开始:

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

Now, I also know that I can add the new style tags to the HTML like this:现在,我也知道我可以像这样将新的样式标签添加到 HTML 中:

$dom->appendChild($ss_elm);
$dom->saveHTML();

However, this would create the following scenario:但是,这将创建以下场景:

<html>
<!--Lots of HTML here-->
</html><style type="text/css">css goes here</style>

The above is essentially pointless;以上基本上毫无意义; the CSS is not parsed and just sits there. CSS 没有被解析,只是坐在那里。

I found this solution online (obviously didn't work):我在网上找到了这个解决方案(显然没有用):

$head = $dom->getElementsByTagName('head');
$head->appendChild($new_elm);
$dom->saveHTML();

Thanks for the help!!谢谢您的帮助!!

EDIT:编辑:

Is it possible?是否有可能?

$head = $dom->getElementsByTagName('head');

Return a DOMNodeList.返回一个 DOMNodeList。 I think it will be better to get the first element like this我认为像这样获得第一个元素会更好

 $head = $dom->getElementsByTagName('head')->item(0);

So $head will be a DOMNode object.所以 $head 将是一个 DOMNode 对象。 So you can use the appendChild method.所以你可以使用 appendChild 方法。

getElementsByTagName返回一个节点数组,所以可能尝试

 $head->[0]->appendChild($new_elm);

This is the solution that worked for me这是对我有用的解决方案

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

You can also add this line at the end to have a clean indentation您还可以在末尾添加此行以进行干净的缩进

// Add a line break between </style> and </head> (optional)
$head->insertBefore($dom->createTextNode("\n"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM