>假设我有一个外部 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>
生成的 HTML 将是:
<html>
<body>
<span class="text"></span>
</body>
</html>
(忽略 DOMDocument 添加的 DOCTYPE 声明(如果不存在)
根据你到底需要它做什么,你可以用另一种方式做到这一点——把目标.HTML文件变成一个.PHP文件,它自己使用一个名为get_span_contents()
的函数填充适当的内容,如下所示:
<html>
<body>
<span class="text">
<?PHP get_span_contents(); ?>
</span>
</body>
</html>
一个缺点是,这将为文档的每个请求生成(可能,取决于缓存方案),而如果您将其分为两个步骤(1.写出 HTML,2。单独提供 HTML)您只会进行一次生成。 根据内容的动态程度或计算成本的微小程度,这可能不是问题。