2014-12-02 71 views
1

我有這個PHP函數從維基百科獲得維基百科文章概要

$function getWikiData() 
{ 
$keyword = $_GET['q']; 
//initiate 
$ch = curl_init(); 
      curl_setopt($ch, CURLOPT_URL, "http://en.wikipedia.org/w/api.php?action=opensearch&search=$keyword&format=xml&limit=1"); 
      curl_setopt($ch, CURLOPT_HEADER, 0); 
      curl_setopt($ch, CURLOPT_USERAGENT, "myCustomBot"); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
      $getData = curl_exec($ch); 
      curl_close($ch); 
} 
      //this output is sent to the template 
      $TMPL['getData'] = $getData; 

得到總結爲預期的輸出圖片,標題,首段,但而不是圖像僅僅是一個損壞的圖像矩形圖標,並將該段落的標題拼湊在一起。 我在做什麼錯?將它需要風格,如果是的話我將如何風格的XML?

+0

正如blue122所示,結果是XML,而不是HTML。您可以用許多不同的方式處理它--PHP提供了大量機制(http://php.net/manual/en/refs.xml.php),其中XSLT是一種。我發現SimpleXml對於這樣的事情非常方便:http://php.net/manual/en/simplexml.examples.php – 2014-12-02 14:04:24

回答

3

此API將返回一個XML,因此您不能僅將其用作HTML數據(即使它在理論上兼容)。

您需要將您的XML轉換爲可打印爲HTML。爲此,您可以使用XSLT。

例如:

<xsl:stylesheet version="1.0" xmlns:php="http://php.net/xsl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="html" encoding="utf-8"/> 
    <xsl:template match="//Image"> 
     Image source : <xsl:value-of select="@source"/> 
    </xsl:template> 
</xsl:stylesheet> 

然後你可以使用XSLTProcessorDOMDocument處理它。

+0

謝謝,讓它工作。我還沒有得到滿意的答覆,但我將其設置爲回答。再次感謝。 – 2014-12-02 14:08:42

相關問題