Home >Backend Development >PHP Tutorial >How to Access CDATA Content with SimpleXMLElement in PHP?
Handling
When working with XML documents containing CDATA tags using SimpleXMLElement, accessing their content can sometimes result in a NULL value. Here's how to resolve this issue:
Accessing CDATA Content
To access the content of CDATA tags correctly, you can either echo the SimpleXMLElement object directly or cast it to a string.
$content = simplexml_load_string( '<content><![CDATA[Hello, world!]]></content>' ); echo (string) $content; // Output: Hello, world!<p><strong>Using LIBXML_NOCDATA</strong></p> <p>Alternatively, you can use the LIBXML_NOCDATA flag when creating the SimpleXMLElement object to suppress the removal of CDATA tags.</p> <pre class="brush:php;toolbar:false">$content = simplexml_load_string( '<content><![CDATA[Hello, world!]]></content>' , null , LIBXML_NOCDATA ); echo (string) $content; // Output: <![CDATA[Hello, world!]]>
Example with Parent Element
If the CDATA tag is inside a parent element, you can access it using the -> operator.
$foo = simplexml_load_string( '<foo><content><![CDATA[Hello, world!]]></content></foo>' ); echo (string) $foo->content; // Output: <![CDATA[Hello, world!]]>
The above is the detailed content of How to Access CDATA Content with SimpleXMLElement in PHP?. For more information, please follow other related articles on the PHP Chinese website!