4

假设我有一个外部 html 页面,我想在我的 php 管理页面的特定标签内附加文本,例如在这个 span 标签内放置杂项文本。

例如:

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

我将如何用 PHP 做到这一点?我正在尝试为这个网站制作一个管理页面,我需要在某些标签内附加文本。我什至不知道从哪里开始,请指出正确的方向。

4

2 回答 2

4

您可以使用 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 声明,如果它不存在)

于 2012-06-28T14:27:36.710 回答
1

Depending on what exactly you need this for, you may be able to do this another way -- make that target .HTML file into a .PHP file instead, with it filling in the appropriate content itself using, let's say, a function called get_span_contents(), like so:

<html>
<body>
  <span class="text">
    <?PHP get_span_contents(); ?>
  </span>
</body>
</html>

One downside is that this will be generated for every request of the document (potentially, depending on caching schemes), whereas if you separated it into two steps (1. Write out the HTML, 2. Serve the HTML separately) you would only ever be doing the generation once. Depending on how dynamic the content is, or how minor the computation cost, that might not be a problem.

于 2012-06-28T14:42:27.040 回答