使用PHP DOM在html标签的开头插入创建的元素 [英] Insert created element at start of html tag using PHP DOM
问题描述
我正在尝试在开始之后立即插入一个HTML < base>
标签 c $ c>< head> 使用dom的页面标签。我试过使用 appendChild
,它只是插入到< / head>
之前,这是不好的。 p>
代码im使用:
$ head = $ dom-> getElementsByTagName ( '头') - >项(0);
$ base = $ dom-> createElement('base');
$ base-> setAttribute('href',$ url);
$ head-> parentNode-> insertBefore($ base,$ head);
这将插入< base>
标签在< head>
之前,这还不错!
任何想法?啤酒正确答案!
$ head = $ dom-> getElementsByTagName '头部') - >项(0);
$ base = $ dom-> createElement('base');
$ base-> setAttribute('href',$ url);
if($ head-> hasChildNodes()){
$ head-> insertBefore($ base,$ head-> firstChild);
} else {
$ head-> appendChild($ base);
}
如果< head>
元素已经有子元素,它在< head>
的第一个元素之前插入< base>
元素儿童。如果< head>
没有孩子,它只会将其追加到< head>
。
I'm trying to insert an HTML <base>
tag immediately after the opening <head>
tag of a page using dom. I've tried using appendChild
which just inserts it before the </head>
which is no good.
Code im using:
$head = $dom->getElementsByTagName('head')->item(0);
$base = $dom->createElement('base');
$base->setAttribute('href', $url);
$head->parentNode->insertBefore($base, $head);
This inserts the <base>
tag before the <head>
, which is still no good!
Any ideas? Beer for the correct answer!
$head = $dom->getElementsByTagName('head')->item(0);
$base = $dom->createElement('base');
$base->setAttribute('href',$url);
if ($head->hasChildNodes()) {
$head->insertBefore($base,$head->firstChild);
} else {
$head->appendChild($base);
}
If the <head>
element already has children, it inserts the <base>
element before <head>
's first child. If <head>
has no children, it just appends it to <head>
.
这篇关于使用PHP DOM在html标签的开头插入创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!