亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

PHP
慕婉清6462132 2021-09-18 17:14:02
我正在嘗試使用 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>有什么建議?
查看完整描述

1 回答

?
偶然的你

TA貢獻1841條經驗 獲得超3個贊

CDATA 部分是一種特殊的文本節點。它們編碼/解碼的次數要少得多,并且保持前導/尾隨空格。因此,DOM 解析器應該從以下兩個示例節點讀取相同的值:


<examples>

  <example>text<example>

  <example><![CDATA[text]]]></example>

</examples>

要創建 CDATA 部分,請使用該DOMDocument::createCDATASection()方法并像任何其他節點一樣附加它。DOMNode::appendChild()返回附加節點,因此您可以嵌套調用:


$properties = [

   [ 'name' => 'qid', 'value' => "1"]

];


$document = new DOMDocument();

$subquestions = $document->appendChild(

    $document->createElement('subquestions')

);


// appendChild() returns the node, so it can be nested

$row = $subquestions->appendChild(

  $document->createElement('row')

);

// append the properties as element tiwth CDATA sections

foreach ($properties as $property) {

    $element = $row->appendChild(

        $document->createElement($property['name'])

    );

    $element->appendChild(

        $document->createCDATASection($property['value'])

    );

}


$document->formatOutput = TRUE;

echo $document->saveXML();

輸出:


<?xml version="1.0"?>

<subquestions>

  <row> 

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

  </row> 

</subquestions>

大多數情況下,使用普通文本節點效果更好。


foreach ($properties as $property) {

    $element = $row->appendChild(

        $document->createElement($property['name'])

    );

    $element->appendChild(

        $document->createTextNode($property['value'])

    );

}

這可以通過使用DOMNode::$textContent屬性進行優化。


foreach ($properties as $property) {

    $row->appendChild(

        $document->createElement($property['name'])

    )->textContent = $property['value'];

}


查看完整回答
反對 回復 2021-09-18
  • 1 回答
  • 0 關注
  • 173 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號