php生成xml时添加CDATA标签

php生成xml时添加CDATA标签方法非常的简单,因为是一个在xml中可以存储各种内容的标签了,下面整理了一个例子希望对各位有帮助.

贴上代码留住伤疤,不要把<![CDATA[ $text]]>当成前后缀,其实它可以是标签,代码如下:

  1. <?php
  2. $dom = new DOMDocument("1.0");
  3. // display document in browser as plain text
  4. // for readability purposes
  5. header("Content-Type: text/plain");
  6. // create root element
  7. $root = $dom->createElement("toppings");
  8. $dom->appendChild($root);
  9. // create child element
  10. $item = $dom->createElement("item");
  11. $root->appendChild($item);
  12. // create text node
  13. $text = $dom->createTextNode("pepperoni");
  14. $item->appendChild($text);
  15. // create attribute node
  16. $price = $dom->createAttribute("price");
  17. $item->appendChild($price);
  18. // create attribute value node
  19. $priceValue = $dom->createTextNode("4");
  20. $price->appendChild($priceValue);
  21. // create CDATA section
  22. $cdata = $dom->createCDATASection(" Customer requests that pizza be sliced into 16 square pieces ");
  23. $root->appendChild($cdata);
  24. // create PI
  25. $pi = $dom->createProcessingInstruction("pizza", "bake()");
  26. $root->appendChild($pi);
  27. // save and display tree
  28. echo $dom->saveXML();
  29. ?>