我想要的是删除XML声明并添加<!DOCTYPE html>
。这是一个代码示例:
$html = new DOMDocument();
$html->formatOutput = true;
$htmlNode = $html->createElement("html");
$html->appendChild($htmlNode);
$htmlNode->appendChild($html->createElement("head"));
$bodyNode = $html->createElement("body");
$bodyNode->setAttribute("data-spy", "scroll");
$bodyNode->setAttribute("data-target", "#myAffix");
$htmlNode->appendChild($bodyNode);
$mainNode = $html->createElement("main");
$bodyNode->appendChild($mainNode);
$gridcellNode = $html->createElement("div");
$gridcellNode->setAttribute("class", "grid-cell");
$mainNode->appendChild($gridcellNode);
$containerFluid = $html->createElement("div");
$containerFluid->setAttribute("class","container-fluid");
$gridcellNode->appendChild($containerFluid);
$html->saveHTMLFile("../article.html");
$html->saveHTML();
$html->save("../article2.html");
第一篇article.html不包含XML声明,但格式不正确(没有缩进)。第二个生成的article2.html有缩进,但也有<?xml version="1.0"?>
。
article.html中的输出:
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<body data-spy="scroll" data-target="#myAffix"><main><div class="grid-cell"><div class="container-fluid"></div></div></main></body>
</html>
第2条中的输出:
<?xml version="1.0"?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body data-spy="scroll" data-target="#myAffix">
<main>
<div class="grid-cell">
<div class="container-fluid"/>
</div>
</main>
</body>
</html>
答案 0 :(得分:1)
您可以使用LIBXML_NOXMLDECL
选项删除XML声明,但这仅适用于Libxml >= 2.6.21
,即:
$html->save("../article2.html", LIBXML_NOXMLDECL);
如果您没有Libxml >= 2.6.21
,则唯一的选择(afaik)是:
$output = $html->saveHTML();
$the_file = "../article2.html";
$html->save($the_file);
file_put_contents($the_file, preg_replace('/<\?xml[^>]+>\s+/', '', file_get_contents($the_file)));