【发布时间】:2021-09-29 21:35:51
【问题描述】:
我正在尝试将 HTML 字符串插入另一个 HTML 元素中,该元素在创建的 DOM 中使用从字符串加载的 HTML 进行解析;
这是我的代码:
PHP:
$str = $attributes["description_text"]; // HTML string
$dom = new DOMDocument; // initialize the domdocument
$dom->loadHTML($str); // load our html into the $dom object
$items = $dom->getElementsByTagName('mark'); // retrieving elements by tag
$gear = $dom->createElement('a', "Lorem ipsum dolor sit amet");
$dom->appendChild($gear);
$output_dom = $dom->saveHTML();
return '<p>'. $output_dom .'</p>';
HTML($str 内容):
Phasellus eu arcu vestibulum, ultrices massa eu, <mark>TOOLTIP</mark> sodales dui.
期望的结果(mark 标签内的a 标签):
<p>Phasellus eu arcu vestibulum, ultrices massa eu, <mark>TOOLTIP<a>Lorem ipsum dolor sit amet</a></mark> sodales dui.</p>
电流输出:
<p>Phasellus eu arcu vestibulum, ultrices massa eu, <mark>TOOLTIP</mark> sodales dui.</p>
<a>Lorem ipsum dolor sit amet</a>
所以现在新字符串附加在整个段落的末尾,而不是mark标签内
【问题讨论】:
-
您在
$items中找到要操作的元素,因此您需要对这些元素而不是整个文档调用appendChild()($dom)