如何防止DOMDocument保存<作为& lt [英] How to keep DOMDocument from saving < as &lt
问题描述
我正在使用simpleXML在一个XML文档中添加一个子节点...当我在我的simpleXML对象上执行print_r时,<
是仍在视图源中显示为<
。但是,在使用DOMDocument将对象保存回XML之后,<
被转换为& lt;
并>
转换为& gt;
I'm using simpleXML to add in a child node within one of my XML documents... when I do a print_r on my simpleXML object, the <
is still being displayed as a <
in the view source. However, after I save this object back to XML using DOMDocument, the <
is converted to <
and the >
is converted to >
关于如何改变这种行为的任何想法?我尝试添加 dom-> substituteEntities = false;
,但这没有任何好处。
Any ideas on how to change this behavior? I've tried adding dom->substituteEntities = false;
, but this did no good.
//Convert SimpleXML element to DOM and save
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = false;
$dom->substituteEntities = false;
$dom->loadXML($xml->asXML());
$dom->save($filename);
这里是我使用<的地方:
Here is where I'm using the <:
$new_hint = '<![CDATA[' . $value[0] . ']]>';
$PrintQuestion->content->multichoice->feedback->hint->Passage->Paragraph->addChild('TextFragment', $new_hint);
问题是我正在使用简单的XML来遍历XML文档中的某些节点,并且如果属性与给定的ID匹配,则会向特定的子节点添加CDATA。然后,在所有处理之后,我使用DOMDocument将XML保存回文件中,这是<会转换为& lt,等等。
The problem, is I'm using simple XML to iterate through certain nodes in the XML document, and if an attribute matches a given ID, a specific child node is added with CDATA. Then after all processsing, I save the XML back to file using DOMDocument, which is where the < is converted to <, etc.
这里是我整个课程文件的链接,因此您可以更好地了解我要完成的工作。具体请参考底部的hint_insert()方法。
Here is a link to my entire class file, so you can get a better idea on what I'm trying to accomplish. Specifically refer to the hint_insert() method at the bottom.
推荐答案
SimpleXML 和php5的 DOM模块使用相同的内部表示形式文档(由 libxml 简化)。您可以在这两种api之间切换,而不必通过simplexml_import_dom()和 dom_import_simplexml( )。
即如果您确实希望/必须在找到元素后使用SimpleXML api执行迭代,则可以切换到DOM api,并在相同文档中创建CData部分。
SimpleXML and php5's DOM module use the same internal representation of the document (facilitated by libxml). You can switch between both apis without having to re-parse the document via simplexml_import_dom() and dom_import_simplexml().
I.e. if you really want/have to perform the iteration with the SimpleXML api once you've found your element you can switch to the DOM api and create the CData section within the same document.
<?php
$doc = new SimpleXMLElement('<a>
<b id="id1">a</b>
<b id="id2">b</b>
<b id="id3">c</b>
</a>');
foreach( $doc->xpath('b[@id="id2"]') as $b ) {
$b = dom_import_simplexml($b);
$cdata = $b->ownerDocument->createCDataSection('0<>1');
$b->appendChild($cdata);
unset($b);
}
echo $doc->asxml();
打印
<?xml version="1.0"?>
<a>
<b id="id1">a</b>
<b id="id2">b<![CDATA[0<>1]]></b>
<b id="id3">c</b>
</a>
这篇关于如何防止DOMDocument保存<作为& lt的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!