假设我有一个外部 html 页面,我想在我的 php 管理页面的特定标记内 append 文本,例如将杂项文本放入此 span 标记内。
例如:
<html>
<body>
<span class="text"></span>
</body>
</html>
我如何用 PHP 做到这一点?我正在尝试为该网站制作一个管理页面,我需要在某些标签内 append 文本。我什至不知道从哪里开始,请指出正确的方向。
最佳答案
您可以使用 PHP 的 DOMDocument 来执行此操作,如下所示:
// Load the HTML document
$doc = new DOMDocument;
$doc->loadHtmlFile( 'htmlpage.html');
// Get the parent node where you want the insertion to occur
$parent = $doc->getElementsByTagName('body')->item( 0);
// Create the child element
$child = $doc->createElement( 'span');
$child->setAttribute( 'class', 'text');
// Append (insert) the child to the parent node
$parent->appendChild( $child);
// Save the resulting HTML
echo $doc->saveHTML();
所以,给定这个 HTML:
<html>
<body>
</body>
</html>
<html>
<body>
<span class="text"></span>
</body>
</html>
(忽略 DOMDocument 添加的 DOCTYPE 声明,如果它不存在)
关于php - 如何使用 PHP 将文本 append 到特定标签内的外部 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246644/