添加到子XML cdata

时间:2013-02-03 19:15:23

标签: php html xml

我想知道如何在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 .']]>',但它不起作用。

提前谢谢。

1 个答案:

答案 0 :(得分:1)

见这里 How to write CDATA using SimpleXmlElement?

从链接的示例中复制:

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());