xml - PHP: How to handle <![CDATA[ with SimpleXMLElement?
Get the solution ↓↓↓I noticed that when usingSimpleXMLElement
on a document that contains those CDATA tags, the content is alwaysNULL
. 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.
Answer
Solution:
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 withLIBXML_NOCDATA
:
$content = simplexml_load_string(
'<content><![CDATA[Hello, world!]]></content>'
, null
, LIBXML_NOCDATA
);
Answer
Solution:
TheLIBXML_NOCDATA
is optional third parameter ofsimplexml_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>";
Answer
Solution:
This is working perfect for me.
$content = simplexml_load_string(
$raw_xml
, null
, LIBXML_NOCDATA
);
Answer
Solution:
When to useLIBXML_NOCDATA
?
I add the issue when transforming XML to JSON.
$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>");
echo json_encode($xml, true);
/* prints
{
"content": {}
}
*/
When accessing the SimpleXMLElement object, It gets the CDATA :
$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>");
echo $xml->content;
/* prints
Hello, world!
*/
I makes sense to useLIBXML_NOCDATA
becausejson_encode
don't access the SimpleXMLElement to trigger the string casting feature, I'm guessing a__toString()
equivalent.
$xml = simplexml_load_string("<foo><content><![CDATA[Hello, world!]]></content></foo>", null, LIBXML_NOCDATA);
echo json_encode($xml);
/*
{
"content": "Hello, world!"
}
*/
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key php
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.