Home >Backend Development >PHP Tutorial >How to Access CDATA Content with SimpleXMLElement in PHP?

How to Access CDATA Content with SimpleXMLElement in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 22:57:12890browse

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!

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