2013-10-02 598 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