SimpleXML不断返回CDATA元素上的内容 [英] SimpleXML keeps returning content on CDATA element
问题描述
另一个CDATA返回内容问题。我已经看到了很多答案,但是即使我全部尝试了,我仍然只能获得内容。
So another CDATA returning content question. I've seen many answers, but even though I tried them all, I still get only content.
更多详细信息:
我有一个xml文件(内部包含许多NewsItem):
I have an xml file (containing many NewsItem inside):
<NewsML>
<NewsItem>
<NewsComponent>
<ContentItem>
<DataContent>
<body>
<body.content>
<![CDATA[<p>This is what I am trying to retrieve</p>]]>
</body.content>
</body>
</DataContent>
</ContentItem>
</NewsComponent>
</NewsItem>
我正在尝试获取body.content的内容。
I am trying to get the content of body.content.
这是我的代码:
$xml = simplexml_load_file('path/to/my/xml.xml',null,LIBXML_NOCDATA);
if(count($xml->children()) > 0){
foreach($xml->children() as $element){
$description = (string)$element->NewsComponent->ContentItem->DataContent->body->body.content;
echo $description;
}
}
echo '<pre>';
print_r($xml);
echo '</pre>';
我的回声返回:
内容
My echo returns: content
即使我确实在xml的print_r中看到了内容,我们也可以在这里看到:
even though I do see the content in the print_r of my xml, as we can see here:
SimpleXMLElement Object
(
[NewsItem] => Array
(
[0] => SimpleXMLElement Object
(
[NewsComponent] => SimpleXMLElement Object
(
[ContentItem] => Array
(
[0] => SimpleXMLElement Object
(
[DataContent] => SimpleXMLElement Object
(
[body] => SimpleXMLElement Object
(
[body.content] => This is what I am trying to retieve
)
)
)
)
)
)
我尝试使用(string)还是不使用
I tried using (string) or not on the element.
我也尝试使用
$xml = simplexml_load_file('path/to/my/xml.xml',null,LIBXML_NOCDATA);
vs
$xml = simplexml_load_file('path/to/my/xml.xml',"SimpleXMLElement",LIBXML_NOCDATA);
vs
$xml = simplexml_load_file('path/to/my/xml.xml');
推荐答案
对于不能为PHP标识符的元素名称(例如 body.content
),则必须使用其他PHP表示法:
For element names which cannot be PHP identifiers (like body.content
), you must use an alternative PHP notation:
$element->NewsComponent->ContentItem->DataContent->body->{'body.content'};
这篇关于SimpleXML不断返回CDATA元素上的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!