开发者

Php DOMDocument Htmlentities problem

I use DOMDocument. My code here.

$dom = new DOMDocument('1.0', 'utf-8');
$textNode = $dom->createTextNode('<input type="text" name="lastName" />');
$dom->appendChild($textNode);
echo $dom->saveHTML开发者_运维知识库();

Output:

&lt;input type="text" name="lastName" /&gt;

I want to this output

<input type="text" name="lastName" />

How can i do?


You need something that actually parses the xml data instead of treating it as "plain" text. DOMDocumentFragment and DOMDocumentFragment::appendXML() can do that.
E.g.

$doc = new DOMDocument;
$doc->loadhtml('<html><head><title>...</title></head>
  <body>
    <form method="post" action="lalala">
      <div id="formcontrols">
      </div>
      <div>
        <input type="submit" />
      </div>
    </form>
  </body>
</html>');

// find the parent node of the new xml fragement
$xpath = new DOMXPath($doc);
$parent = $xpath->query('//div[@id="formcontrols"]');
// should test this first
$parent = $parent->item(0);

$fragment = $doc->createDocumentFragment();
$fragment->appendXML('<input type="text" name="lastName" />');
$parent->appendChild($fragment);

echo $doc->savehtml(); 


Change createTextNode with createElement. Text nodes are for text :)

$dom = new DOMDocument('1.0', 'utf-8');
$textNode = $dom->createElement('input');
$textNode->setAttribute('type', 'text');
$textNode->setAttribute('name', 'lastName');
$dom->appendChild($textNode);
echo $dom->saveHTML();


look at the documentation one of the first things is says

"A quick note to anyone who is using character entities (e.g. ©) in this, and finding them automatically escaped. The correct thing to do here is to use the createEntityReference method (e.g. createEntityReference("copy");), and then appendChild this entity between text nodes. "

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜