gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:57:21 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com