tags:

views:

277

answers:

1

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.

+3  A: 

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;

$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);
Josh Davis
No, PHP skips CDATA completely for some reason.Any other ideas?
Angelo
Then it's a bug. Upgrade PHP/libxml until it works (I've never had any problems with CDATA and SimpleXML.) You may want to try your luck with LIBXML_NOCDATA otherwise.
Josh Davis
@Josh Davis, Right on. Without the LIBXML_NOCDATA, the XML comes in as false - regardless of how it's done. I was able to prove that out with both creation methods... $x = new SimpleXMLElement('<content><![CDATA[Hello, world!]]></content>', LIBXML_NOCDATA); $y = simplexml_load_string('<content><![CDATA[Hello, world!]]></content>', "SimpleXMLElement", LIBXML_NOCDATA);print_r($y);Without that option, they're both null.Just wanted to back up your assertion.
Inkspeak
Thanks, guys! LIBXML_NOCDATA did the trick! :)
Angelo
Thanks, LIBXML_NOCDATA worked for me too
Liam