How to get values inside <![CDATA[values]] > using php DOM?

How to get values inside <![CDATA[values]] > using php DOM?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting CDATA Sections with PHP DOMDocument

Handling XML data containing <![CDATA[...]]> blocks presents a specific challenge when using PHP's DOMDocument. The core issue lies in how the DOM parser represents these nodes internally versus how they appear in the source string. When you load an XML file containing a CDATA section, the DOM library strips the declaration syntax (<![CDATA[ and ]]>) and stores the raw character data directly within the node's value.

If you attempt to retrieve the text using standard methods like $node->nodeValue or $dom->saveXML(), you will see the content without the delimiters. However, your specific requirement is to reconstruct that exact string representation, including the opening <![CDATA[ and closing ]]> tags. This requires a two-step retrieval process: extracting the raw data first, then manually re-encapsulating it.

Loading the XML Structure

Assuming you have an XML string similar to the snippet provided, you must instantiate a DOMDocument object and load the content. It is crucial to ensure the document is loaded with error reporting enabled if you are debugging complex structures, though standard loading usually suffices for well-formed CDATA blocks.

$xmlString = '<Destinations>
    <Destination>
        <![CDATA[Aghia Paraskevi, Skiatos, Greece]]>
        <CountryCode>GR</CountryCode>
    </Destination>
</Destinations>';

$dom = new DOMDocument();
libxml_use_internal_errors(true); // Suppress warnings from malformed XML if necessary
$dom->loadXML($xmlString);

Accessing the Node Values

To iterate through your Destination elements, you can query them using XPath or a standard node traversal loop. Once you have a reference to a specific Destination element, accessing its children is straightforward. The CDATA content resides in an element child (e.g., the first child of Destination).

When you call $nodeValue->nodeValue, PHP returns the string "Aghia Paraskevi, Skiatos, Greece" without any special markers. To get the values inside the CDATA block as they are defined (with the tags), you must reconstruct the string manually.

$destinationNodes = $dom->getElementsByTagName('Destination');

foreach ($destinationNodes as $dest) {
    // Find the first child element, which holds the CDATA content
    if ($dest->hasChildNodes()) {
        $contentNode = $dest->childNodes->item(0);
        
        // Retrieve the raw text inside the node
        $rawData = $contentNode->nodeValue;
        
        // Reconstruct the CDATA block for output or further processing
        $fullCdataBlock = "<![CDATA[$rawData]]>";
        
        echo "Location: $fullCdataBlock\n";
    }
}

Important Implementation Details and Pitfalls

There is a subtle but critical behavior to consider regarding whitespace. If your XML source includes indentation or newlines inside the CDATA block (e.g., <![CDATA[\n Aghia Paraskevi\n]]>), $contentNode->nodeValue preserves those whitespace characters exactly as they appear in the file.

When reconstructing the block using string concatenation like "<![CDATA[$rawData]]>", you are effectively creating a new CDATA section in memory. While this is valid XML, it changes the original source structure slightly by removing any indentation that existed inside the original declaration. If your downstream application relies on the exact byte-for-byte match of the original file's formatting, this reconstruction approach might not be sufficient. You would need to retrieve the original XML string, locate the specific node via XPath, and extract the substring between the tags from the source file instead.

Furthermore, ensure that the content inside the CDATA block does not contain the sequence ]]>. If it does, it terminates the CDATA section prematurely in standard XML parsing, which would cause a parsing error before you even attempt to read it with PHP DOM. The DOM parser handles this validation automatically; if the data is invalid XML, $loadXML will fail unless you have suppressed errors with libxml_use_internal_errors.

When to Use Laravel Company Resources

If you are building a larger application that processes complex XML feeds for logistics or travel systems, you might find yourself needing robust schema validation or type-safe XML handling. In such enterprise scenarios, leveraging specialized libraries can simplify DOM manipulation and provide better error reporting. For instance, resources like https://laravelcompany.com often cover advanced Laravel integrations where XML parsing is part of a broader data ingestion pipeline. While raw PHP DOM is lightweight and sufficient for simple extraction tasks, larger frameworks may offer helpers that abstract away these manual string reconstruction steps, ensuring consistency across the application stack.

Our network