read cdata from a rss feed

纵饮孤独 提交于 2019-11-28 14:24:27
hakre

Tell SimpleXML to convert CDATA into normal texts:

$homepage = 'http://www.forbes.com/news/index.xml';
$movies = simplexml_load_file($homepage, "SimpleXMLElement", LIBXML_NOCDATA);

That should do it for you, using simplexml_load_file instead of file_get_contents.

Related Answer: Removing cdata in simplehtmldom.

The above "fix" will work, but is entirely unnecessary.

SimpleXML objects contain a lot of "magic", and are not designed to be viewed using print_r; the CDATA is safely in your object, but won't show up unless you ask for it in the right way.

If you run echo (string)$movies->channel->title; you should get "Forbes.com: News" as you would expect.

Note the (string), which tells PHP to explicitly convert the "magic" SimpleXMLElement into a string. If you don't do this, you'll actually be getting another SimpleXMLElement object back - otherwise my example wouldn't work because $movies->channel would be a string.

It's good practice to always use (string) when accessing elements or attributes from SimpleXML, as some functions will choke if they are expecting a string and you give them a SimpleXML object instead, and serializing or session storage will certainly fail.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!