从数据库转义 XML 以进行输出


Escape XML from database for output

我正在尝试使用 XML 创建一个zend_form,传递的 XML 包含所有标签,所以我不能使用 htmlspecialchars() 因为标签<>会被编码,这是我不想要的。 有没有简单的方法可以只对作为标签的文本值(标签之间的内容)的元素进行编码?

$xml = sprintf('<?xml version="1.0" encoding="UTF-8"?><form><localhost><formmanager><formpage><elements>%s</elements></formpage></formmanager></localhost></form>',
                                $r['form_template']);
$config = new Zend_Config_Xml($xml, 'localhost');
$form = new Zend_Form($config->formmanager->$formName);

保存在数据库上的 xml 的摘录:

<questionTechnicalServices>
<type>MultiCheckbox</type>
<options>
<class>rule2 standard basic2 starter business spotlight</class>
<label>Technical Services</label>
<multioptions>
<item-ContractLaboratoryandtestingServices>Contract Laboratory and testing Services</item-ContractLaboratoryandtestingServices>
<item-ContractRDDesignandEngineering>Contract R&D, Design and Engineering</item-ContractRDDesignandEngineering>
<item-ContractSterilization>Contract Sterilization</item-ContractSterilization>
<item-CoilingRespoolingWinding>Coiling/Respooling/Winding</item-CoilingRespoolingWinding>
<item-OthersTechnicalServices>Others</item-OthersTechnicalServices>
</multioptions>
</options>
</questionTechnicalServices>

研发需要更改为&amp;,就像任何>或<等一样。>

问候

保存在数据库中的 XML 无效。元素值应在存储之前进行转义。不这样做会导致您现在遇到的问题。

但是,您可以通过将其作为 HTML 加载到 DOM 中并将其保存回字符串来更正它。尽管由于它已经无效,但不能保证任何解析器都会执行您想要的操作。