简体   繁体   中英

Set nodeValue content html in DOMDocument

I have created new element with dom object:

$doc = new \DOMDocument();
$link = $doc->createElement('a'); 
$link->setAttribute('href', '/#');
$link.nodeValue = '<b>Text</b>';
$html = $this->doc->saveHTML();

This variable "$html" contains content:

<a href="/#">&lt;b&gt;Text&lt;/b&gt;</a>

I want to output:

<a href="/#"><b>Text</b></a>

How can I set "nodeValue" correctly? Is it possible to do it this way?

Thank you very much.

By using a DOMDocumentFragement and it's appendXML() method

<?php
$doc = new \DOMDocument();
$link = $doc->appendChild($doc->createElement('html'))
    ->appendChild( $doc->createElement('body') )
    ->appendChild( $doc->createElement('a') );
$link->setAttribute('href', '/#');


$fragment = $doc->createDocumentFragment();
$fragment->appendXML('<b>text</b>');
$link->appendChild($fragment);


echo $doc->saveHTML();

prints

<html><body><a href="/#"><b>text</b></a></body></html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM