将HTML代码插入特定位置

时间:2014-02-19 11:21:18

标签: php html insert

我知道这个主题随处可见,但他们的问题不是我想要的。我想在页面加载之前插入一些HTML代码而不触及页面中的原始代码。

假设我的标题由一个名为render_header()的函数呈现:

function render_body() {
return "<body>
    <div class='container'>
    <div class='a'>A</div>
    <div class='b'>B</div>
    </div>
    </body>";
}

从现在开始,我想使用PHP 插入HTML代码而不编辑render_body()。我想要一个将一些div插入container'div 的函数。

render_body();
<?php *//Insert '<div class="c" inside div container* ?>

2 个答案:

答案 0 :(得分:1)

我唯一能想到的是打开输出缓冲,然后使用DOMDocument类读取整个缓冲区,然后对其进行更改。值得一些阅读脚本中提供的文档(http://www.php.net/manual/en/book.dom.php)...

即:

<?php


function render_body() {
return "<body>
    <div class='container'>
    <div class='a'>A</div>
    <div class='b'>B</div>
    </div>
    </body>";
}  

$dom = new DOMDocument();

$dom->loadHTML(render_body());

// get body tag
$body = $dom->getElementsByTagName('body')->item(0);

// add a new element at the end of the body
$element = $dom->createElement('div', 'My new element at the end!');
$body->appendChild($element);

echo $dom->saveHTML(); // echo what is in the dom

?>

编辑:

根据CD001的建议,我已经测试了这段代码并且有效。

答案 1 :(得分:1)

作为使用XPath的替代方法 - 这应该在render_body()的输出中加载到XML(DOMDocument)对象并创建一个XPath对象来查询HTML,这样您就可以轻松找出你想要插入新HTML的地方。

这可能只有在您使用XML格式良好的HTML时才有效。

//read in the document
$xml = new DOMDocument();
$xml->loadHTML(render_body());

//create an XPath query object
$xpath = new DOMXpath($xml);

//create the HTML nodes you want to insert
// using $xml->createElement() ...

//find the node to which you want to attach the new content
$xmlDivClassA = $xpath->query('//body/div[@class="a"]')->item(0);
$xmlDivClassA->appendChild( /* the HTML nodes you've previously created */ );

//output
echo $xml->saveHTML();

因为我不得不参考文档而花了一些时间...最近JQuery太多了,它破坏了我操纵DOM的能力而没有查找:\