我有这个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 的样式?
此 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>
然后,您可以使用XSLTProcessor
和DOMDocument
来处理它。