Home >Backend Development >PHP Tutorial >How to Extract CDATA Content Using SimpleXMLElement in PHP?

How to Extract CDATA Content Using SimpleXMLElement in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 12:58:021021browse

How to Extract CDATA Content Using SimpleXMLElement in PHP?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn