如果你打算在PHP中處理XML數據,就需要一個XML函式庫為你擷取資料。例如解析RSS feed或是模式比對(尋找XHTML影像或是元素)。
SimpleXML擴充提供了一個非常直覺的API,更容易將XML轉換成物件和遍歷元素。唯一的缺點就是在記憶體中載入整個文件或是非常大的XML文件,它的效能可能是一個問題。
如果效能是個考慮因素,你可以去使用XMLReader。 XMLReader是一個XML解析器,它透過在載入過程中遍歷每個節點,在而不是在記憶體中載入整個文件。
下面的程式碼使用簡單的XML可以從我的網站取得最新的RSS。在我的伺服器上,我已經使用Curl庫處理HTTP連接,因為它支援伺服器託管並且更安全。
<ol class="dp-xml"> <li class="alt"><span><span class="tag"><?</span><span class="tag-name">php</span><span> </span></span></li><li><span> </span></li><li class="alt"><span>function load_file($url) { </span></li><li><span>$</span><span class="attribute">ch</span><span> = </span><span class="attribute-value">curl_init</span><span>($url); </span></li><li class="alt"><span>#Return http response in string </span></li><li><span>curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); </span></li><li class="alt"><span>$</span><span class="attribute">xml</span><span> = </span><span class="attribute-value">simplexml_load_string</span><span>(curl_exec($ch)); </span></li><li><span>return $xml; </span></li><li class="alt"><span>} </span></li><li><span> </span></li><li class="alt"><span>$</span><span class="attribute">feedurl</span><span> = </span><span class="attribute-value">'http://naveenbalani.com/index.php/feed/'</span><span>; </span></li><li><span>$</span><span class="attribute">rss</span><span> = </span><span class="attribute-value">load_file</span><span>($feedurl); </span></li><li class="alt"><span> </span></li><li><span>foreach ($rss-</span><span class="tag">></span><span>channel-</span><span class="tag">></span><span>item as $item) { </span></span></li> <li class="alt"> <span>echo "</span><span class="tag"><</span><span class="tag-name">h2</span><span class="tag">></span><span>" . $item-</span><span class="tag">></span><span>title . "</span><span class="tag"></</span><span class="tag-name">h2</span><span class="tag">></span><span>"; </span> </li> <li> <span>echo "</span><span class="tag"><</span><span class="tag-name">p</span><span class="tag">></span><span>" . $item-</span><span class="tag">></span><span>description . "</span><span class="tag"></</span><span class="tag-name">p</span><span class="tag">></span><span>"; </span> </li> <li class="alt"><span>} </span></li> <li><span> </span></li> <li class="alt"> <span class="tag">?></span><span> </span> </li> </ol>
http://css.dzone.com/news/parsing-xml-data-php