【问题标题】:XML CDATA not returning properly with simplexml_load_string() nor SimpleXMLElement() (PHP)XML CDATA 未使用 simplexml_load_string() 或 SimpleXMLElement() (PHP) 正确返回
【发布时间】:2013-05-14 16:12:28
【问题描述】:

我可以撤回任何非 CDATA 字段。但不是汇总字段。我已经用尽了我所知道的一切来尝试。下面是我能得到的最接近的结果,摘要字段返回空白。如果我当然对整个文件进行 var_dump,它确实会返回,但是我无法访问特定字段。请帮忙!谢谢!

XML 示例

<?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";
    }

【问题讨论】:

    标签: php xml cdata


    【解决方案1】:

    你的代码有一个小问题,simplexml_load_string documentation 指的是:

    采用格式良好的 XML 字符串并将其作为对象返回。

    并且您提供 SimpleXMLElement 作为第一个参数。只需将代码中的那一行替换为这一行:

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

    【讨论】:

    • 感谢您的快速响应,但是,当它到达该行时,它会出错并退出。控制台日志在打印出第一个“标题”后实际上抛出以下错误...“NetworkError: 500 Internal Server Error - xxx
    • 尤里卡!你快到了 Rolando... 一个小调整: echo (string) 'Summary: ' 。 simplexml_load_string($entries->summary->children()->asXML(), null, LIBXML_NOCDATA) 。 "
      \n"; $entry 必须是 $entries ...但是您所做的其他一切都是正确的...谢谢!你让我开心。
    • @user2379061 我的错,当我使用您的代码时,我将foreach 上的变量名称从$entries 更改为$entry。为了原始代码的一致性,我更新了答案:)
    猜你喜欢
    • 2023-03-05
    • 2015-02-18
    • 2011-02-27
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多