XML CDATA not returning properly with simplexml_load_string() nor SimpleXMLElement() (PHP)

元气小坏坏 提交于 2019-12-04 05:54:55

问题


I can pull back any of the non-CDATA fields. But not the summary field. I've exhausted everything i know to try. Below is as close as i could get, with the summary field returning blank. It does return if i do a var_dump of the whole file of course, but then i can't access specific fields. Please help! Thanks!

XML Sample

<?xml version="1.0" encoding="utf-8"?>
<zatom:feed xmlns:zatom="http://www.w3.org/2005/Atom" xmlns:z4m="http://namespaces.zope.com/zc/syndication" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us">
<zatom:updated>2013-05-09T14:46:12Z</zatom:updated>
<zatom:title>Partner feeds</zatom:title>
<zatom:author><zatom:name>Zillow</zatom:name></zatom:author>
<zatom:id>urn:Zillow:wsls20130509:0000</zatom:id>
<zatom:entry z4m:content-type="zc.z4mcontent.story" z4m:status="published">
<zatom:updated>2013-05-09T14:46:12Z</zatom:updated>
<z4m:dateline term="Syndicated"/>
<z4m:source term="Zillow"/>
<zatom:rights>&#169; 2013</zatom:rights>
<zatom:category scheme="http://namespaces.zope.com/zc/z4m/section" term="real_estate_news" />
<zatom:title type="text">Harnessing the Power of Online Home Searches</zatom:title>
<zatom:summary type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><![CDATA[Harnessing the Power of Online Home Searches]]></div></zatom:summary></zatom:entry>
</zatom:feed>

PHP

$str_xml = file_get_contents('http://content.zillow.com/feeds/partners/wsls/');
    $obj_xml = new SimpleXMLElement($str_xml);

    foreach( $obj_xml->children('zatom', true)->entry as $entries ) {
        echo (string) 'Title: ' . $entries->title . '<br />';
            echo (string) 'Summary: ' . simplexml_load_string($entries->summary, null, LIBXML_NOCDATA) . "<br />\n";
    }

回答1:


You have a minor problem in your code, simplexml_load_string documentation refers:

Takes a well-formed XML string and returns it as an object.

and you're providing a SimpleXMLElement as the first argument. Just replace that line from your code with this one:

echo (string) 'Summary: ' . simplexml_load_string($entries->summary->children()->asXML(), null, LIBXML_NOCDATA) . "<br />\n";


来源:https://stackoverflow.com/questions/16547992/xml-cdata-not-returning-properly-with-simplexml-load-string-nor-simplexmleleme

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