[英]How can I get PHP simplexml to save < as itself instead of <
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: 基本上,我有一个脚本可以在各个地方更新xml文档。但是,我需要文本位于CDATA中。因此,我尝试了以下操作:
$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; 不幸的是,当我将XML保存回文件时,cdata中的<和>分别作为它们的<和$ 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! 在完成我的simple_xml对象的print_r之后,<本身在源代码中出现!
It must be the domsave that is converting it into the entity code... any ideas how to disable this? 必须是将domsave转换为实体代码...如何禁用此功能的任何想法?
//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);
Like I said in the comments, SimpleXML is very limited in the control it gives you over the DOM nodes. 就像我在评论中说的那样,SimpleXML在它为您提供的DOM节点的控制上非常受限制。 Here is an example on how to replace a DOMText node with a DOMCDATASection node.
这是有关如何用DOMCDATASection节点替换DOMText节点的示例 。
$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 有关如何使用DOM的冗长示例, 请在此处查看我的答案,在此处查看 更多信息
Can't you use html_entity_decode
function before sending it to your parser? 您不能在将其发送到解析器之前使用
html_entity_decode
函数吗? It will convert <
and >
back to <
and >
它将
<
和>
转换回<
和>
The parser can't cope with CDATA sections? 解析器无法处理CDATA部分? 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.
在这种情况下,它不是XML解析器,因此您需要编写一个生成类似XML的输出的工具,而不是XML工具。 (Or fix the parser so it becomes an XML parser)
(或修复解析器,使其成为XML解析器)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.