2014-12-02 68 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

相关问题