1

我想知道如何在 xml child 中添加 cdata?我得到了这个代码:

$errors = array();
if(isset($_POST['newtopic'])){
    $topicname = preg_replace('/[^A-Za-z]/', '', $_POST['topicname']);
    $textarea = $_POST['textarea'];
    $desc = $_POST['desc'];
    $startedby = $_POST['startedby'];
    $tn = $_POST['topicname'];

    if($topicname == ''){
        $errors[] = 'You`re topic title is missing!';
    }
    if($topicname == ''){
    $errors[] = 'You`re textarea is missing!';
}


    if(count($errors) == 0){
        $xml = new SimpleXMLElement('<topic></topic>');
        $xml->addChild('textarea', $textarea);
        $xml->addChild('desc', $desc);
        $xml->addChild('startedby', $startedby);
        $xml->addChild('date', $date);
        $xml->addChild('topicname', $tn);
        $xml->asXML('topics/sitenews/' . $topicname . '.xml');
        header('Location: sitenews.php');
        die;
    }
}

我只想将 cdata 添加到 $textarea 部分,我尝试过已经使用'<![CDATA['. $textarea .']]>'但它不起作用。

先感谢您。

4

1 回答 1

1

请参阅此处 如何使用 SimpleXmlElement 编写 CDATA?

从链接的示例中复制:

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

$doc = new SimpleXMLExtended($xml); 
$element = $doc->addChild('response'); 
$node_note = $element->addChild('note'); 
$node_note->addCData('my cdata guff'); 
var_dump($doc->asXML()); 
于 2013-02-03T19:22:19.447 回答