Insert created element at start of html tag using PHP DOM

百般思念 提交于 2019-12-12 14:04:12

问题


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!


回答1:


$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>.



来源:https://stackoverflow.com/questions/3180113/insert-created-element-at-start-of-html-tag-using-php-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!