PHP DOMDocument:insertBefore,如何让它工作?

pun*_*bit 5 php domdocument

我想在给定元素之前放置一个新的节点元素.我正在使用insertBefore,但没有成功!

这是代码,

<DIV id="maindiv">

<!-- I would like to place the new element here -->

<DIV id="child1">

    <IMG />

    <SPAN />

</DIV>

<DIV id="child2">

    <IMG />

    <SPAN />

</DIV>
Run Code Online (Sandbox Code Playgroud)

//$div is a new div node element,
//The code I'm trying, is the following:

$maindiv->item(0)->parentNode->insertBefore( $div, $maindiv->item(0) ); 

//Obs: This code asctually places the new node, before maindiv
//$maindiv object(DOMNodeList)[5], from getElementsByTagName( 'div' )
//echo $maindiv->item(0)->nodeName gives 'div'
//echo $maindiv->item(0)->nodeValue gives the correct data on that div 'some random text'
//this code actuall places the new $div element, before <DIV id="maindiv>
Run Code Online (Sandbox Code Playgroud)

http://pastie.org/1070788

任何形式的帮助表示赞赏,谢谢!

jmz*_*jmz 5

如果maindiv来自getElementsByTagName(),那么$maindiv->item(0)是id = maindiv的div.所以你的代码工作正常,因为你要求它在maindiv之前放置新的div.

为了使它像你想要的那样工作,你需要得到maindiv的孩子:

$dom = new DOMDocument();
$dom->load($yoursrc);
$maindiv = $dom->getElementById('maindiv');
$items = $maindiv->getElementsByTagName('DIV');
$items->item(0)->parentNode->insertBefore($div, $items->item(0));
Run Code Online (Sandbox Code Playgroud)

请注意,如果您没有DTD,PHP不会返回任何带有getElementsById的内容.要使getElementsById起作用,您需要拥有DTD或指定哪些属性是ID:

foreach ($dom->getElementsByTagName('DIV') as $node) {
    $node->setIdAttribute('id', true);
}
Run Code Online (Sandbox Code Playgroud)


pun*_*bit 0

找到了解决办法:

            $child = $maindiv->item(0);
            
            $child->insertBefore( $div, $child->firstChild ); 
Run Code Online (Sandbox Code Playgroud)

我不知道这有多大意义,但是,它确实有效。