DOMDocument XML .lsg 中的小于和大于符号

我正在尝试使用 PHP 脚本向 lsg 文件(由 XML 组成)添加一些新元素。然后将 lsg 文件导入到limesurvey。问题是我无法正确添加诸如 < 和 > 之类的字符,而我需要添加这些字符。它们仅显示为它们的实体引用(例如 < 和 >),在导入到limesurvey 时无法正常工作。如果我手动将实体引用更改为 < 和 >


我尝试使用 PHP DOMDocument 来做到这一点。我的代码看起来类似于:


$dom = new DOMDocument();

$dom->load('template.lsg');


$subquestions = $dom->getElementById('subquestions');


$newRow = $dom->createElement('row');

$subquestions->appendChild($newRow);


$properties[] = array('name' => 'qid', 'value' => "![CDATA[1]]");


foreach ($properties as $prop) {

    $element = $dom->createElement($prop['name']);

    $text = $dom->createTextNode($prop['value']);

    $startTag = $dom->createEntityReference('lt');

    $endTag = $dom->createEntityReference('gt');

    $element->appendChild($startTag);

    $element->appendChild($text);

    $element->appendChild($endTag);

    $supplier->appendChild($element);

}


$response = $dom->saveXML();

$dom->save('test.lsg');

那一行的结果是这样的:


<row>

        <qid>&lt;![CDATA[7]]&lt;</qid>

</row>

虽然它应该是这样的:


<row>

    <qid><![CDATA[7]]></qid>

</row>

有什么建议?


慕婉清6462132
浏览 158回答 1
1回答

偶然的你

CDATA 部分是一种特殊的文本节点。它们编码/解码的次数要少得多,并且保持前导/尾随空格。因此,DOM 解析器应该从以下两个示例节点读取相同的值:<examples>&nbsp; <example>text<example>&nbsp; <example><![CDATA[text]]]></example></examples>要创建 CDATA 部分,请使用该DOMDocument::createCDATASection()方法并像任何其他节点一样附加它。DOMNode::appendChild()返回附加节点,因此您可以嵌套调用:$properties = [&nbsp; &nbsp;[ 'name' => 'qid', 'value' => "1"]];$document = new DOMDocument();$subquestions = $document->appendChild(&nbsp; &nbsp; $document->createElement('subquestions'));// appendChild() returns the node, so it can be nested$row = $subquestions->appendChild(&nbsp; $document->createElement('row'));// append the properties as element tiwth CDATA sectionsforeach ($properties as $property) {&nbsp; &nbsp; $element = $row->appendChild(&nbsp; &nbsp; &nbsp; &nbsp; $document->createElement($property['name'])&nbsp; &nbsp; );&nbsp; &nbsp; $element->appendChild(&nbsp; &nbsp; &nbsp; &nbsp; $document->createCDATASection($property['value'])&nbsp; &nbsp; );}$document->formatOutput = TRUE;echo $document->saveXML();输出:<?xml version="1.0"?><subquestions>&nbsp; <row>&nbsp;&nbsp; &nbsp; <qid><![CDATA[1]]></qid>&nbsp; </row>&nbsp;</subquestions>大多数情况下,使用普通文本节点效果更好。foreach ($properties as $property) {&nbsp; &nbsp; $element = $row->appendChild(&nbsp; &nbsp; &nbsp; &nbsp; $document->createElement($property['name'])&nbsp; &nbsp; );&nbsp; &nbsp; $element->appendChild(&nbsp; &nbsp; &nbsp; &nbsp; $document->createTextNode($property['value'])&nbsp; &nbsp; );}这可以通过使用DOMNode::$textContent属性进行优化。foreach ($properties as $property) {&nbsp; &nbsp; $row->appendChild(&nbsp; &nbsp; &nbsp; &nbsp; $document->createElement($property['name'])&nbsp; &nbsp; )->textContent = $property['value'];}
打开App,查看更多内容
随时随地看视频慕课网APP