How to Access CDATA Content with SimpleXMLElement in PHP?
Nov 24, 2024 pm 10:57 PMHandling <![CDATA[ with SimpleXMLElement in PHP
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon

Announcement of 2025 PHP Situation Survey
