douxian5963 2016-01-16 10:54
浏览 141

PHP DOM RemoveChild不起作用

I have the following code:

<?php
$li = ('www.somesite.com');     
$ht = file_get_contents($li);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($ht);
$divs = $dom->getElementsByTagName('section');
    foreach ($divs as $div){
        if(preg_match('/\btresc\b/', $div->getAttribute('id'))) {


            $chapter = $div->getElementsByTagName('div1')->item(0);

            $oldchapter = $div->removeChild($chapter);

            echo $oldchapter;
            }


        }


?>

I'm trying to remove <div class="div1">.*</div> with <section id="tresc">.*</section> However, I get the following error: Fatal error: Call to a member function removeChild() on a non-object. Does anybody know what I'm doing wrong here? Any help is greatly appreciated!

  • 写回答

1条回答 默认 最新

  • doufendi9063 2016-01-16 11:32
    关注

    Don't include the quotes in your preg_match(), getAttribute() will just give you the plain value without quotes:

    if(preg_match('/tresc/', $div->getAttribute('id'))) {
    

    You should switch to simple string comparison instead as there is no real value in using a regex.

    if($div->getAttribute('id') == 'tresc') {
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!