2014-02-26 62 views
0

我遇到了一個問題,當我存儲$ msgIn(string)並且它包含像&符或貨幣值之類的smybols時,它將不會保存並在符號之前切斷,是有一種方法可以告訴它在CDATA標籤中包裝消息?通過PHP向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>` 

任何建議/幫助非常感謝。

回答

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