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

标签 php append getelementbyid

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

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

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

最佳答案

就像克里斯在评论中提到的那样,尝试使用 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);

或者,如果您已经有要 append 的 HTML 字符串,则可以 create a document fragment像这样:

$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);

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

关于PHP:通过 ID 将 html 内容 append (添加)到现有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32193133/

相关文章:

javascript - 当输入更改元素值时隐藏元素的通用函数

JavaScript:获取下拉列表的值

javascript - 如何选择在 Angular 中动态加载的 html 元素?

php - SQL/PHP - 关键更新

php - 当有人使用 twitter api 和 php 发布推文时如何收到通知

php 调用存储过程并出现 pdo 问题

jQuery:唯一的 Each() var append

php - 如何刷新网站缓存?

javascript - 在标签中 append div 作为帮助文本。在每个 radio 组及其包装器 div 中

javascript - 向生成的 URL 添加 anchor