I noticed that when using SimpleXMLElement
on a document that contains those CDATA tags, the content is always NULL
. How do I fix this?
Also, sorry for spamming about XML here. I have been trying to get an XML based script to work for several hours now...
<content><![CDATA[Hello, world!]]></content>
I tried the first hit on Google if you search for "SimpleXMLElement cdata", but that didn't work.
You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
);
echo (string) $content;
// or with parent element:
$foo = simplexml_load_string(
'<foo><content><![CDATA[Hello, world!]]></content></foo>'
);
echo (string) $foo->content;
You might have better luck with LIBXML_NOCDATA
:
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
, null
, LIBXML_NOCDATA
);
The LIBXML_NOCDATA
is optional third parameter of simplexml_load_file()
function. This returns the XML object with all the CDATA data converted into strings.
$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);
echo "<pre>";
print_r($xml);
echo "</pre>";
Fix CDATA in SimpleXML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With