如何使用dom解析器添加php标签

nfo*_*nfo 5 php dom

我创建了一些带有php doms功能的HTML模板,现在我想在我的模板中添加一些php标签,即

$input = $this->dom->createElement('input');
$input->setAttribute("type", "text");
$input->setAttribute("name", $name);
$input->setAttribute("class", "input");
$input->setAttribute("id", $name);
$input->setAttribute("value", '<?=$foo->bar; ?>');
Run Code Online (Sandbox Code Playgroud)

我的问题是,dom解析器逃脱了php行..

<input type="text" name="id" class="input" id="id" value="\&lt;?=$content-&gt;id;?&gt;" />
Run Code Online (Sandbox Code Playgroud)

还有另一种方法吗?

Gor*_*don 3

您需要一份处理指令

$php = $dom->createProcessingInstruction('php', 'echo $foo->bar;');
Run Code Online (Sandbox Code Playgroud)

完整示例:

$dom = new DOMDocument;
$dom->loadXml('<html><head><title>Test</title></head><body/></html>');
$dom->getElementsByTagName('body')->item(0)->appendChild(
    $dom->createProcessingInstruction('php', 'echo $foo->bar;')
);
$dom->format = TRUE;
echo $dom->saveXML();
Run Code Online (Sandbox Code Playgroud)

结果:

<?xml version="1.0"?>
<html>
  <head>
    <title>Test</title>
  </head>
  <body>
    <?php echo $foo->bar;?>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)