php - DOMDocument 避免初始 xml 标记
问题描述
问题:
如何避免 DOMDocument 创建初始 xml-tag?:
<?xml version="1.0"?>
想要的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My site</title>
</head>
<body>
</body>
</html>
使用 DOMDocument 生成的代码:
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>My site</title>
</head>
<body></body>
</html>
我的脚本:
<?php
/**
* Ref:
* https://stackoverflow.com/questions/19482826/using-domdocument-to-create-elements-in-an-html-file
* https://www.php.net/manual/en/domimplementation.createdocumenttype.php
*/
// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;
// Doctype
$dtd = $imp->createDocumentType(
'html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
);
// Base document
$doc = $imp->createDocument("", "", $dtd);
$doc->formatOutput = true;
/**
* Construct tag skeleton.
*/
// [L-1]
$html=$doc->appendChild(
$doc->createElementNS("http://www.w3.org/1999/xhtml","html")
);
$html->setAttribute("lang", "en");
$html->setAttribute("xml:lang", "en");
$doc->appendChild($html);
// [L-2]
$head=$html->appendChild(
$doc->createElement('head')
);
// [L-3]
$title=$head->appendChild(
$doc->createElement(
'title',
"My site"
)
);
// [L-2]
$body=$html->appendChild(
$doc->createElement('body')
);
// Save
echo $doc->saveHTML();
$doc->save("auto_produced_xhtml.xhtml");
解决方案
您可以使用saveHTMLFile();
而不是save()
...另存为 HTML 文件。代替
$doc->save("auto_produced_xhtml.xhtml");
和
$doc->saveHTMLFile("auto_produced_xhtml.xhtml");
推荐阅读
- elasticsearch - 如何检测elasticsearch是否启用了动态字段
- r - 错误:SET_STRING_ELT() 的值必须是 'CHARSXP' 而不是 dplyr group_by 中的“字符”
- reactjs - 如何在反应中创建一个自动滚动的表格?
- php - 隐藏未使用/零结果以显示格式(第二个可读数据格式功能)
- typescript - 带有 Typescript 的 Luxon:TS2339:“DateTime”类型上不存在属性“c”
- java - CaptainCasa 框架:自由度导出不起作用
- javascript - ExtJS - 组合框多选填充
- python - 清理数据框中的文本
- graphql - 错误:无法在 graphql-codegen 中合并 GraphQL 指令“abstractEntity”
- c++ - 通过 lambda 表达式将函数转发到 std::thread