PHP:如何处理 <![CDATA[ 与 SimpleXMLElement?

问题描述:

我注意到在包含这些 CDATA 标签的文档上使用 SimpleXMLElement 时,内容总是 NULL.我该如何解决这个问题?

I noticed that when using SimpleXMLElement on a document that contains those CDATA tags, the content is always NULL. How do I fix this?

另外,很抱歉在这里乱发有关 XML 的信息.我一直试图让基于 XML 的脚本工作几个小时......

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>

如果您搜索SimpleXMLElement cdata",我在 Google 上尝试了第一次点击,但没有成功.

I tried the first hit on Google if you search for "SimpleXMLElement cdata", but that didn't work.

您可能没有正确访问它.您可以直接输出它或将其转换为字符串.(在本例中,强制转换是多余的,因为无论如何 echo 都会自动执行)

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;

使用 LIBXML_NOCDATA 可能会更好:

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
    , null
    , LIBXML_NOCDATA
);