问题
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 <
and >
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:
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
回答2:
Can't you use html_entity_decode function before sending it to your parser? It will convert <
and >
back to <
and >
回答3:
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)
来源:https://stackoverflow.com/questions/3418796/how-can-i-get-php-simplexml-to-save-as-itself-instead-of-lt