【问题标题】:PHP XML CDATA parsingPHP XML CDATA 解析
【发布时间】:2013-10-02 12:36:18
【问题描述】:

我在查询网络服务(雅虎天气)时遇到问题。感谢这个很酷的论坛,我找到了以下hint。然而,我无法找回我的价值。

我正在使用提取 CDATA 部分

$conditionIcon = $weatherXmlObject->xpath("//item/description");
$dom = new DOMDocument();
$dom->loadHTML($conditionIcon); // or you can use loadXML
$xml = simplexml_import_dom($dom);
$imgSrc = (string)$xml->body->img['src'];
echo $imgSrc;

$imgSrc 始终为空。

描述如下

<description><![CDATA[
<img src="http://l.yimg.com/a/i/us/we/52/28.gif"/><br />
<b>Current Conditions:</b><br />
Mostly Cloudy, 50 F<BR />
<BR /><b>Forecast:</b><BR />
Fri - Partly Cloudy. High: 62 Low: 49<br />
Sat - Partly Cloudy. High: 65 Low: 49<br />
<br />
<a    href="http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html">Full Forecast at Yahoo! Weather</a><BR/><BR/>
(provided by <a href="http://www.weather.com" >The Weather Channel</a>)<br/>
]]></description>

【问题讨论】:

    标签: php xml cdata yahoo-api yahoo-weather-api


    【解决方案1】:

    问题在于解析器忽略了 CDATA 块中的所有数据。您必须在另一个 DOMDocument 中加载描述正文。

    【讨论】:

    • 你的意思是$conditionIcon = $weatherXmlObject->xpath("//item/description"); $dom = 新的 DOMDocument(); $dom->loadHTML($conditionIcon); $xml = simplexml_import_dom($dom); $newDoc = 新 DOMDocument(); $newDoc->loadHTML((string)$xml->body); $newXml = simplexml_import_dom($newDoc); $imgSrc = (string)$newXml->img['src'];回声 $imgSrc;
    【解决方案2】:

    好的,我解决了这个问题,但使用了一个正则表达式(感谢page 也讨论了这个问题):

    // retrieve link to condition image - in description element
    $xml = simplexml_load_string($weather_feed, 'SimpleXMLElement', LIBXML_NOCDATA); 
    $description = $xml->channel->item->description;
    //preg match regular expression to extract weather icon
    $imgpattern = '/src="(.*?)"/i';
    preg_match($imgpattern, $description, $matches);
    $aExport['img_url'] = $matches[1];
    

    干杯

    【讨论】:

      猜你喜欢
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2012-09-11
      • 1970-01-01
      • 2012-01-19
      相关资源
      最近更新 更多