开发者

PHP DOMDocument: insertBefore, how to make it work?

I would like to place a new node element, before a given element. I'm using insertBefore for that, without success!

Here's the code,

<DIV id="maindiv">

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

<DIV id="child1">

    <IMG />

    <SPAN />

</DIV>

<DIV id="child2">

    <IMG />

    <SPAN />

</DIV>

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

$ma开发者_运维技巧indiv->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>

http://pastie.org/1070788

Any kind of help is appreciated, thanks!


If maindiv is from getElementsByTagName(), then $maindiv->item(0) is the div with id=maindiv. So your code is working correctly because you're asking it to place the new div before maindiv.

To make it work like you want, you need to get the children of maindiv:

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

Note that if you don't have a DTD, PHP doesn't return anything with getElementsById. For getElementsById to work, you need to have a DTD or specify which attributes are IDs:

foreach ($dom->getElementsByTagName('DIV') as $node) {
    $node->setIdAttribute('id', true);
}


From scratch, this seems to work too:

$str = '<DIV id="maindiv">Here is text<DIV id="child1"><IMG /><SPAN /></DIV><DIV id="child2"><IMG /><SPAN /></DIV></DIV>';
$doc = new DOMDocument();
$doc->loadHTML($str);
$divs = $doc->getElementsByTagName("div");
$divs->item(0)->appendChild($doc->createElement("div", "here is some content"));
print_r($divs->item(0)->nodeValue);


Found a solution:

            $child = $maindiv->item(0);
            
            $child->insertBefore( $div, $child->firstChild ); 

I don't know how much sense this makes, but well, it worked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜