使用PHP文档向头部添加样式标记

使用PHP文档向头部添加样式标记,php,css,domdocument,appendchild,createelement,Php,Css,Domdocument,Appendchild,Createelement,我想创建一组标记并将其添加到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->createAtt

我想创建一组
标记并将其添加到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);
$dom->appendChild($ss_elm);
$dom->saveHTML();
现在,我还知道我可以向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);
$dom->appendChild($ss_elm);
$dom->saveHTML();
但是,这将创建以下场景:

<html>
<!--Lots of HTML here-->
</html><style type="text/css">css goes here</style>
谢谢你的帮助

编辑: 可能吗

$head = $dom->getElementsByTagName('head');
返回一个域名列表。我认为最好得到第一个元素,像这样

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

所以$head将是一个DOMNode对象。因此,您可以使用appendChild方法。

getElementsByTagName
返回一个节点数组,因此可能需要尝试

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

这就是对我有效的解决方案

// 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);
//创建包含给定CSS的新标记
$new_elm=$dom->createElement('style','css在这里');
$new_elm->setAttribute('type','text/css');
//在文档头中插入新标记
$head=$dom->getElementsByTagName('head')->项(0);
$head->appendChild($new_elm);
也可以在末尾添加这一行,以获得清晰的缩进

// Add a line break between </style> and </head> (optional)
$head->insertBefore($dom->createTextNode("\n"));
//在和之间添加换行符(可选)
$head->insertBefore($dom->createTextNode(“\n”);

你所说的“不起作用”是什么意思?另外,在执行
$new\u elm->appendChild($elm\u type\u attr)时,可能会出现错误
因为
DomeElement
没有
appendChild
方法。当我说“不起作用”时,我的意思是没有显示编辑的HTML,只有一个空白页面。但是,
$new_elm->appendChild()工作。Patouche更准确地说,它返回的DomainNodeList对象的行为类似于array(关于这一点,您可以检查迭代器和ArrayObject,它们是SPL对象),这就是为什么您可以像array一样访问它并对其进行迭代的原因