XMLWriter无法写入<;头部>;要素


XMLWriter cannot write into <head> element

Iv发现不可能将任何内容(文本或其他元素)写入head元素,例如

$XML = new XMLWriter();
$XML->openMemory();
$XML->startElement("head");
$XML->writeAttribute("id","head");
$XML->text("lable");
$XML->endElement();
$XML->startElement("div");
$XML->text("div");
$XML->endElement();
echo $XML->outputMemory();

将输出身体中的元素,而不是头部,但它会生成正确的属性:

<html>
<head id="head">
</head>
<body>
lable
<div>
div
</div>
</body>
</html>

为什么我不能在脑子里写任何内容?

HTML不支持在其<head>中存在文本或内容相关元素。来自W3C推荐:

HEAD元素包含有关当前文档的信息,例如其标题、可能对搜索引擎有用的关键字以及不被视为文档内容的其他数据。

通常,要写入HTML头的主要元素是<title>元素和任何<meta>元素。我认为以下方法可行:

$XML = new XMLWriter();
$XML->openMemory();
$XML->startElement("head");
$XML->writeAttribute("id","head");
$XML->startElement("title");
$XML->text("My HTML page");
$XML->endElement();
$XML->endElement();
$XML->startElement("div");
$XML->text("div");
$XML->endElement();
echo $XML->outputMemory();

运行与您上面提供的完全相同的脚本,我得到以下结果:

<head id="head">lable</head><div>div</div>

由于您的代码甚至没有提到bodyhtml元素,因此可能对PHP代码生成的输出进行了后期处理?