此php代码可以正常工作,但如何将CDATA添加到内容节点?
<?php
$xml = new DomDocument("1.0", "UTF-8");
$xml->load('xmldata.xml');
$title = $_POST['title'];
$avtor = $_POST['avtor'];
$date = $_POST['date'];
$category = $_POST['category'];
$content = $_POST['content'];
$rootTag = $xml->getElementsByTagName("root")->item(0);
$postingTag = $xml->createElement("posting");
$titleTag = $xml->createElement("title", $title);
$avtorTag = $xml->createElement("avtor", $avtor);
$dateTag = $xml->createElement("date", $date);
$categoryTag = $xml->createElement("category", $category);
$contentTag = $xml->createElement("content", $content);
$postingTag->appendChild($titleTag);
$postingTag->appendChild($avtorTag);
$postingTag->appendChild($dateTag);
$postingTag->appendChild($categoryTag);
$postingTag->appendChild($contentTag);
$rootTag->appendChild($postingTag);
$xml->formatOutput = true;
$xml->save('xmldata.xml');
答案 0 :(得分:7)
DOM分隔节点创建和追加。您可以使用文档的方法创建节点,并使用父节点的方法将其附加。
以下是一个例子:
$document = new DOMDocument();
$root = $document->appendChild(
$document->createElement('element-name')
);
$root->appendChild(
$document->createCDATASection('one')
);
$root->appendChild(
$document->createComment('two')
);
$root->appendChild(
$document->createTextNode('three')
);
echo $document->saveXml();
输出:
<?xml version="1.0"?>
<element-name><![CDATA[one]]><!--two-->three</element-name>
DOMNode::appendChild()
和类似方法返回附加节点,因此您可以将它们与DOMDocument::create*()
调用结合起来。
答案 1 :(得分:3)
CDATA或CDATA部分?
$cdata = 'This is my character data!';
首次使用createElement('tagname', 'cdata')
的第二个参数 - 嘿,你已经在这里做了:
$contentTag = $xml->createElement("content", $content);
^^^^^^^^
表示第二个createCDATASection()
并将其作为子项附加到创建的元素:
$contentTag = $xml->createElement("content", $content);
$contentTag->appendChild($xml->createCDATASection($cdata);