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

Rya*_*auk 5 php append getelementbyid

我需要使用 PHP 通过 ID 搜索元素,然后将 html 内容附加到它。这看起来很简单,但我是 php 新手,找不到合适的函数来执行此操作。

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

我只是不知道下一步该怎么做。任何帮助,将不胜感激。

Bac*_*ics 4

就像 chris 在他的评论中提到的那样,尝试使用DOMNode::appendChild,这将允许您向所选元素添加一个子元素,并允许DOMDocument::createElement实际创建元素,如下所示:

$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);
Run Code Online (Sandbox Code Playgroud)

或者,如果您已经有要附加的 HTML 字符串,则可以创建一个文档片段,如下所示:

$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);
Run Code Online (Sandbox Code Playgroud)

请注意,PHP 无法访问使用 JavaScript 添加的任何元素。