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

标签 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>

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

http://pastie.org/1070788

感谢任何形式的帮助,谢谢!

最佳答案

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

为了让它像你想要的那样工作,你需要得到 maindiv 的 child :

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

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

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

关于PHP DOMDocument : insertBefore, 如何让它工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3386882/

相关文章:

php - Woocommerce 和 PayPal 账单地址

php - 如果链接值为 1,则如何激活链接;如果为 0,则链接未激活,请使用单选按钮

php - PHP到sqlite3-无法上传

php - Paypal 网络支付标准 - 退款。它们可以通过 Api 完成吗?

php - 使用 php domdocument 获取 YouTube 视频的标题

php - 如果字段为空,如何跳过 RSS 项目?

javascript - 不在html标记中设置onclick属性的原因

xml - Excel vba 解析复杂 XML

php - 如果使用 domdocument 后存在术语,则获取标签的内容

javascript - 为什么通过缓存变量访问 DOM 会更快?