Home > Article > Backend Development > How to Properly Handle CDATA Tags with SimpleXMLElement in PHP?
Handling CDATA Tags in SimpleXMLElement
In PHP, the SimpleXMLElement class provides a powerful interface for working with XML documents. However, users may encounter difficulties when dealing with CDATA tags, as their content is often returned as NULL.
To resolve this issue and properly retrieve the CDATA content, there are several approaches to consider. One straightforward method is to directly output the CDATA as a string:
$content = simplexml_load_string( '<content><![CDATA[Hello, world!]]></content>' ); echo (string) $content;
Alternatively, you can cast the CDATA content to a string:
$content = simplexml_load_string( '<content><![CDATA[Hello, world!]]></content>' ); echo strval($content);
In both cases, the result will be the original CDATA content, "Hello, world!".
For more control, you can also utilize the LIBXML_NOCDATA flag in simplexml_load_string:
$content = simplexml_load_string( '<content><![CDATA[Hello, world!]]></content>' , null , LIBXML_NOCDATA );
This method strips the CDATA tags, leaving only the unformatted content.
The above is the detailed content of How to Properly Handle CDATA Tags with SimpleXMLElement in PHP?. For more information, please follow other related articles on the PHP Chinese website!