php - 将 CDATA 添加到 xml 节点

标签 php xml

此 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');

最佳答案

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*() 调用组合。

关于php - 将 CDATA 添加到 xml 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31240495/

相关文章:

sql-server - 跳过 SQL 生成的 XML 中的 NULL 参数

php - 在 WooCommerce 中取消设置有条件的自定义结帐字段

php - 根据另一个表逐步更新一个表

php - 如何在Laravel View 中输出ElasticSearch查询

javascript - 如何在运行其他代码后使用javascript转到上一页?

xml - Linq to XML - 仅在某些情况下创建 Xelement

java - 使用 Java 解析 ALM XML 数据

php - MYSQL INSERT INTO 不插入数据或抛出错误

android - 自定义小部件 : Error inflating class

sql-server - 从 SQL Server 中的同一 xml 列获取多个值