开发者

getting cdata (html) in a dom xml element

开发者 https://www.devze.com 2023-03-28 04:44 出处:网络
I am creating an XML document with DOM and got HTML funny characters like ä and å from a databas开发者_Python百科e that i need to put inside an element. But i can\'t get it to work really.

I am creating an XML document with DOM and got HTML funny characters like ä and å from a databas开发者_Python百科e that i need to put inside an element. But i can't get it to work really.

What is the proper way to add CDATA HTML in an element so that my output becomes like this:

<TRANSLATIONS>
    <DENMARK>
        <ERRORADDRESSLINE1REQUIRED><![CDATA[&auml; &aring;]]></ERRORADDRESSLINE1REQUIRED>
    </DENMARK>
</TRANSLATIONS>

using this:

$sData = "<![CDATA[" . $value . "]]>";
$objLabel = $objXmlDoc->createElement($label, $sData);

doesn't really do the trick and appending $objXmlDoc->createCDATASection($value) creates an element next to another label and not inside a label.

What do i overlook?


You have to append the CDATA section to the element you want it in:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->appendChild($dom->createElement('translations'))
        ->appendChild($dom->createElement('denmark'))
            ->appendChild($dom->createElement('error'))
                ->appendChild($dom->createCDataSection('&auml; &aring;'));

$dom->formatOutput = true;
echo $dom->saveXml();

Output:

<?xml version="1.0" encoding="utf-8"?>
<translations>
  <denmark>
    <error><![CDATA[&auml; &aring;]]></error>
  </denmark>
</translations>

But there should be no need to put ä and å into CDATA sections when you are using UTF-8:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->appendChild($dom->createElement('translations'))
        ->appendChild($dom->createElement('denmark'))
            ->appendChild($dom->createElement('error', 'ä and å'));

$dom->formatOutput = true;
echo $dom->saveXml();

Outputs perfectly valid:

<?xml version="1.0" encoding="utf-8"?>
<translations>
  <denmark>
    <error>ä and å</error>
  </denmark>
</translations>
0

精彩评论

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