views:

69

answers:

3

Basically I have a script that updates an xml document in various places... However, I need the text to be in CDATA... So I attempted this:

                $PrintQuestion->content->multichoice->feedback->hint->Passage->Paragraph->addChild('TextFragment', '<![CDATA[' . $value[0] . ']]>');

Unfortunately when I save the XML back to file, the < and > in cdata come up as their respective < and $gt; codes is there a way to avoid this?

Note: Our parser doesn't know how to read the &lt; and &gt; codes, so this is a serious issue

after doing a print_r of my simple_xml object, the < appears as itself in the source code!

It must be the domsave that is converting it into the entity code... any ideas how to disable this?

        //Convert SimpleXML element to DOM and save
        $dom = new DOMDocument('1.0');
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = false;
        $dom->loadXML($xml->asXML());
        $dom->save($filename);
+1  A: 

Can't you use html_entity_decode function before sending it to your parser? It will convert &lt and &gt back to < and >

Sarfraz
+3  A: 

Like I said in the comments, SimpleXML is very limited in the control it gives you over the DOM nodes. Here is an example on how to replace a DOMText node with a DOMCDATASection node.

$dom = new DOMDocument;
$dom->loadXML('<root><a>foo</a></root>');
$a = $dom->documentElement->childNodes->item(0);
$a->replaceChild(
    $dom->createCDATASection('bar'),
    $a->childNodes->item(0)
);
echo $dom->saveXml($a); // <a><![CDATA[bar]]></a>

For a lengthy example on how to use DOM see my answer here and some more here

Gordon
+1  A: 

The parser can't cope with CDATA sections? In that case it is not an XML parser, so you need to write a tool that generates an XML-like output instead of an XML tool. (Or fix the parser so it becomes an XML parser)

David Dorward