EastsideDev
EastsideDev

Reputation: 6639

Unintended formatting using PHP DomDocument

I am trying to include a formatted element in an XML document, using PHP's DomDocument class.

I wrote the following function:

function awstAddFormattedElement ($mySessionParams, $parentElement, $elementName, $elementValue) {
    $xmlDoc = $mySessionParams['xmlDoc'];

    $element = $xmlDoc->createElement($elementName,$elementValue);
    $element = $parentElement->appendChild($element);

    $myessionParams['element'] = $element;
    return $mySessionParams;
}

The problem is that when I call it, entities in the $elementValue are automatically encoded, and the service I'm calling is rejecting it.

$elementValue = '<![CDATA['.
                    '<p>blah, blah, blah.</p>'.
                ']]>';

So, when I do:

awstAddFormattedElement ($mySessionParams, $parentElement, 'FormattedContent', $elementValue)

I expect to see something like this in the resulting XML:

<FormattedContent><![CDATA[<p>blah, blah, blah.</p>]]></FormattedContent>   

Instead, I'm getting the following:

<FormattedContent>&lt;![CDATA[&lt;p&gt;blah, blah, blah.&lt;/p&gt;]]&gt;</FormattedContent>

Any ideas?

Upvotes: 1

Views: 40

Answers (1)

Phil
Phil

Reputation: 164912

For CDATA sections, you have to use DOMDocument::createCDATASection, eg

$element = $xmlDoc->createElement($elementName);
$element->appendChild($xmlDoc->createCDATASection($elementValue));

$parentElement->appendChild($element);

Your $elementValue argument should only contain the raw string, eg

$elementValue = '<p>blah, blah, blah.</p>';

Upvotes: 1

Related Questions