更新
我认为之前给出的信息无关紧要,所以我只需要知道如何将下面的字符串添加到注释位置的 HTML 中。
.PHP
$string = "some text";
.HTML
<div id="wrapper">
<div>some content</div>
<div>some content</div>
<div>some content</div>
<!--Place where I need to add the string same as it is-->
</div>
您没有发布完整的代码,但我假设您有一个调用
query
方法的DOMXPath
。
编辑:您确实发布了完整的代码,并且正在使用DOMXPath
此方法返回一个
DOMNodeList
,一个包含 DOMNode
s 的列表。
只能在单个DOMNode
上调用appendChild
,因为该方法未在DOMNodeList
上定义。
使用它从DOMNodeList
获取第一个DOMNode
:
$wrapper->item(0)->appendChild($newpost);
这将从列表中获取可调用 appendChild
方法的第一项。
插入模板
此行不起作用:
$newpost = "<?php echo include('/assets/includes/post-template.php'); ?>";
因为这是你尝试作为DOM/HTML插入的PHP代码
请改为执行以下操作:
// New temp document
$templateDoc = new DOMDocument();
// Load your template file into this document
$templateDoc->loadHTMLFile($DOCUMENT_ROOT . '/assets/includes/post-template.php')
// Get all immediate children of your template document
$templateElements = $doc->getElementsByTagName('*');
在你的if
语句中:
foreach($templateElements as $templateElement){
// Append all children to your wrapper
$wrapper->item(0)->appendChild($templateElement);
}