duanfu3884 2015-08-24 23:09
浏览 256

PHP:通过ID将html内容附加(添加)到现有元素

I need to search for an element by ID using PHP then appending html content to it. It seems simple enough but I'm new to php and can't find the right function to use to do this.

$html = file_get_contents('http://example.com');
$doc = new DOMDocument(); 
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$descBox = $doc->getElementById('element1');

I just don't know how to do the next step. Any help would be appreciated.

  • 写回答

2条回答 默认 最新

  • duansha7025 2015-08-25 04:48
    关注

    Like chris mentioned in his comment try using DOMNode::appendChild, which will allow you to add a child element to your selected element and DOMDocument::createElement to actually create the element like so:

    $html = file_get_contents('http://example.com');
    libxml_use_internal_errors(true);
    $doc = new DOMDocument(); 
    $doc->loadHTML($html);
    //get the element you want to append to
    $descBox = $doc->getElementById('element1');
    //create the element to append to #element1
    $appended = $doc->createElement('div', 'This is a test element.');
    //actually append the element
    $descBox->appendChild($appended);
    

    Alternatively if you already have an HTML string you want to append you can create a document fragment like so:

    $html = file_get_contents('http://example.com');
    libxml_use_internal_errors(true);
    $doc = new DOMDocument(); 
    $doc->loadHTML($html);
    //get the element you want to append to
    $descBox = $doc->getElementById('element1');
    //create the fragment
    $fragment = $doc->createDocumentFragment();
    //add content to fragment
    $fragment->appendXML('<div>This is a test element.</div>');
    //actually append the element
    $descBox->appendChild($fragment);
    

    Please note that any elements added with JavaScript will be inaccessible to PHP.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败