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'];
}
- 1 回答
- 0 關注
- 173 瀏覽
添加回答
舉報