DOMDocument在标记之前插入<h1>标记

时间:2017-12-29 18:53:31

标签: html dom domdocument

如何在关闭<h1>代码之前插入</body>代码?

$html = '
    <html>
    </head>
    <body>
        <span>Blalala</span>
    </body>
    </html>
';

$dom = new DOMDocument();
$dom->loadHtml($html);
//$body= $dom->getElementsByTagName('body');
//Somehow insert h1 tag before </body> tag
echo $doc->savehtml($html);

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码。在文档DOMNode :: appendChild中 - 在子项末尾添加新子项

<?php
$html = '
    <html>
    <head>
    </head>
    <body>
        <span>Blalala</span>
    </body>
    </html>
';

$dom = new DOMDocument();
$dom->loadHtml($html);
$body = $dom->getElementsByTagName('body')->item(0);
$hNode = $dom->createElement("h1");
$body->appendChild($hNode);
echo $dom->savehtml();