1

I wonder how can i add cdata in xml child? i got this code:

$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;
    }
}

i wanna add the cdata to $textarea part only, i tried already use '<![CDATA['. $textarea .']]>' but its not working.

Thank you in advance.

  • Good news is: You do not need to add CDATA, you can add just text as well. SimpleXML will encode it for you properly. Otherwise, see the duplicate question. – hakre Feb 06 '13 at 09:50

1 Answers1

1

See here How to write CDATA using SimpleXmlElement?

Copied from the linked example:

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()); 
Community
  • 1
  • 1
chill0r
  • 1,127
  • 2
  • 10
  • 26
  • Can you please connect it to my code? i already seen this page.. i using new child not new simple xml element – יותם דהן Feb 03 '13 at 19:25
  • i've tried this $cdata = $xml->addChild('textarea', $textarea); $cdata->addCData($textarea); – יותם דהן Feb 03 '13 at 19:30
  • 1
    Please do not duplicate answers like this. If an answer already exists, point it out in the comments or provide it as a dupe once you have reached 3k reputation – Gordon Feb 06 '13 at 09:53