Search code examples
phpelementheadxmlwriter

XMLWriter cannot write into <head> element


Iv discovered that it is impossible to write any content (text or another elements) into head element, for example

$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();

will output elements in body, not in head, but it makes correct attributes:

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

Why i cannot write any content into head?


Solution

  • HTML does not support the presence of text or content-related elements in its <head>. From the W3C recommendation:

    The HEAD element contains information about the current document, such as its title, keywords that may be useful to search engines, and other data that is not considered document content.

    Typically, the main elements you would want to write to the HTML head are the <title> element and any <meta> elements. I presume that the following would work:

    $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();