2013-10-02 599 views
0

我在查询Web服务(雅虎天气)时遇到问题。感谢这个很酷的论坛,我发现了以下hint。不过,我无法找回我的价值。PHP XML 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提取CDATA部分总是空的。

描述是这样的

<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> 

回答

0

OK,我解决了这个问题,但使用正则表达式(感谢这个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]; 

干杯

1

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

+0

你的意思 $ conditionIcon = $ weatherXmlObject- >的xpath( “//项目/描述”); $ dom = new DOMDocument(); $ dom-> loadHTML($ conditionIcon); $ xml = simplexml_import_dom($ dom); $ newDoc = new DOMDocument(); $ newDoc-> loadHTML((string)$ xml-> body); $ newXml = simplexml_import_dom($ newDoc); $ imgSrc =(string)$ newXml-> img ['src']; echo $ imgSrc; – AntonSack