通过PHP问题将带有CDATA的节点添加到XML

时间:2014-02-26 22:30:45

标签: php xml

我遇到一个问题,当我存储$ msgIn(字符串)并且它包含像&符号或货币值的smybols时它不会保存并且在符号之前切断,有没有办法告诉它包装CDATA标签中的消息?

$xml = @simplexml_load_file($this->currentChatLogFile);
$message = $xml->messages->addChild("message", $msgIn);
$message->addAttribute("timestamp", date("U"));
$message->addAttribute("pid", $uidIn);
$message->addAttribute("poster", $uname);
$message->addAttribute("ip", $_SERVER['REMOTE_ADDR']);
$xml->saveXML($this->currentChatLogFile);

目前在我提交Test & test2时收到此信息:

`<?xml version="1.0" encoding="UTF-8"?>
<chatlog created="1393450231">
<messages>
<message timestamp="1393453404" pid="16" poster="core" ip="127.0.0.1">Test </message>
</messages>
</chatlog>`

任何建议/帮助都非常感谢。

1 个答案:

答案 0 :(得分:2)

<?php
    class ExSimpleXML extends SimpleXMLElement {
      public function addCData($cdata_text) {
        $node = dom_import_simplexml($this); 
        $no   = $node->ownerDocument; 
        $node->appendChild($no->createCDATASection($cdata_text)); 
      } 
    }




    $xml = new ExSimpleXML('<root/>');
    $xml->item= NULL;
    $xml->item->addCData('CDATA TEST');
    $xml->saveXML("file.xml");

?>

基于的例子 http://www.php.net/manual/pt_BR/simplexmlelement.addchild.php