Handling CDATA with SimpleXMLElement in PHP
When dealing with CDATA tags in an XML document parsed by SimpleXMLElement, extracting the content can be challenging. By default, accessing a node containing a CDATA section via ->content returns NULL.
Solution 1: Direct Output or Casting
To retrieve the CDATA content, you can either output it directly or cast it to a string. Both methods effectively convert the CDATA to a valid PHP string:
$content = simplexml_load_string( '<content><![CDATA[Hello, world!]]></content>' ); echo (string) $content; // Output: 'Hello, world!'
Solution 2: LIBXML_NOCDATA
Alternatively, you can specify the LIBXML_NOCDATA option during parsing to ignore all CDATA sections and treat them as regular text nodes:
$content = simplexml_load_string( '<content><![CDATA[Hello, world!]]></content>' , null , LIBXML_NOCDATA ); echo (string) $content; // Output: 'Hello, world!'
With these methods, you can successfully handle CDATA in XML documents using SimpleXMLElement, providing you with access to their content.
The above is the detailed content of How to Extract CDATA Content Using SimpleXMLElement in PHP?. For more information, please follow other related articles on the PHP Chinese website!