Hi guys,

I'm using DOMDocument to create an XML document but I can't see how to create an element who's value is encapsulated in CDATA.

Example:

<name><![CDATA[john smith]]></name>

I am currently trying to use DOMDocument::createCDATASection() but it does not allow me to create an element name.

Is this possible at all using DOMDocument?

    Sure; but you have to create the element first, then put the CDATA node inside it (they're two separate things).

      But the CDATA is not a node like most as it does not seem to be contained within it's own element.

      createCDATASection() will return an object. In this case I cannot use this value as the value included into the second parameter of createElement().

      Example of what I tried that doesn't work.

      	$xml = new DOMDocument( "1.0", "UTF-8" );
      	$base = $xml->createElement( 'history' );
      	$cdata_value = $xml->createCDATASection( 'John Smith' );
      	$xml->createElement( 'name', $cdata_value );
      

      I am still at a loss of how I include the CDATA with an element like:

      <name><![CDATA[john smith]]></name>

        I think you're looking for something like this?

        <?php
        header('Content-Type: text/xml');
        $xml = new DOMDocument( "1.0", "UTF-8" );
        $base = $xml->appendChild($xml->createElement( 'history' ));
        $name = $base->appendChild($xml->createElement('name'));
        $name->appendChild($xml->createCDATASection( 'John Smith' ));
        $xml->formatOutput = true;
        echo $xml->saveXML();
        
          doublehops wrote:

          But the CDATA is not a node like most as it does not seem to be contained within it's own element.

          A CDATA section is a kind of node; an element is another kind of node. (And plain text, attributes, comments, and processing instructions are yet other different kinds of node.)

            Thanks guys, I got it. My confusion was that the CDATA should be a child of the element and not the content. Therefore I should have been using appendChild() rather than createElement() to add the CDATA.

              a year later
              NogDog;10946284 wrote:

              I think you're looking for something like this?

              <?php
              header('Content-Type: text/xml');
              $xml = new DOMDocument( "1.0", "UTF-8" );
              $base = $xml->appendChild($xml->createElement( 'history' ));
              $name = $base->appendChild($xml->createElement('name'));
              $name->appendChild($xml->createCDATASection( 'John Smith' ));
              $xml->formatOutput = true;
              echo $xml->saveXML();
              

              Thanks! Exactly what I needed

                Write a Reply...