php - 如何使用 PHP 将文本 append 到特定标签内的外部 html 文件?

标签 php html string append

假设我有一个外部 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>

resulting HTML would be :

<html>
<body>
<span class="text"></span>
</body>
</html>

(忽略 DOMDocument 添加的 DOCTYPE 声明,如果它不存在)

关于php - 如何使用 PHP 将文本 append 到特定标签内的外部 html 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246644/

相关文章:

string - 什么是最适合用于比较电视节目标题的字符串距离算法?

javascript - 按第一个空格分割字符串

string - 在 dafny 中更新不可变字符串的最佳方法

php - MySQL PHP - 根据不同位置选择 WHERE

php - 在非对象日期格式上调用成员函数 format()

php - PHP数组中的内存优化

javascript - 如何使用单选按钮值设置复选框选择限制

javascript - 更改 GET 请求后显示的 URL

php - 当每行有多个用逗号分隔的数据时,如何计算各行的值总数?

jquery - 如何使用 jQuery 获取剩余的剩余空间