加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何使用PHP将文本附加到特定标记内的外部html文件?

发布时间:2020-12-13 17:20:04 所属栏目:PHP教程 来源:网络整理
导读:假设我有一个外部html页面,我想在我的php管理页面中添加特定标记内的文本,例如将杂项文本放在此span标记内. 例如: htmlbodyspan class="text"/span/body/html 我怎么用PHP做到这一点?我正在尝试为这个网站创建一个管理页面,我需要在某些标签内附加文本.我
假设我有一个外部html页面,我想在我的php管理页面中添加特定标记内的文本,例如将杂项文本放在此span标记内.

例如:

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

我怎么用PHP做到这一点?我正在尝试为这个网站创建一个管理页面,我需要在某些标签内附加文本.我甚至不知道从哪里开始,请指出我正确的方向.

解决方法

您可以使用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不存在,则忽略DOMDocument添加的DOCTYPE声明)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读