我正在尝试使用 php 将下面的 XML 提要转换为 HTML 表格
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" version="2.0">
<channel>
<title>
Latest consumer reviews on abc.com from 28/09/2015
</title>
<link>https://www.example.com</link>
<description>
<![CDATA[ bla bla bla bla. ]]>
</description>
<item>
<title>2015 AUDI A1 SPORTBACK TFSI</title>
<link>
http://localhost/frontend/www/audi/a1/2015/
</link>
<pubDate>1443607871</pubDate>
<enclosure length="" type="image/jpeg"/>
<guid isPermaLink="true">
http://localhost/frontend/www/audi/a1/2015/
</guid>
<date>30/09/2015</date>
<time>10:11</time>
<id>1</id>
<image>
https://example.com/audi.jpg
</image>
</item>
<item>
<title>2015 BMW 3series</title>
<link>
http://localhost/frontend/www/bmw/3/2015/
</link>
<pubDate>1444117968</pubDate>
<enclosure length="" type="image/jpeg"/>
<guid isPermaLink="true">
http://localhost/frontend/www/bmw/3/2015/
</guid>
<date>06/10/2015</date>
<time>07:52</time>
<id>2</id>
<image>
https://example.com/bmw.jpg
</image>
</item>
</channel>
</rss>
在我的 php 代码中我有这个
$baseurl = 'http://localhost/frontend/www/';
$url = $baseurl.'comment/rss/comments/?t='.time().'&l=4';
$xml = new SimpleXMLElement($url, 0, TRUE);
foreach($xml->channel AS $x) {
print_r($x);
}
但是当我 print_r
时我输出的是什么不是 <item>
的完整数组.我得到的就是这个
SimpleXMLElement Object ( [title] => Latest consumer reviews on example.com from 28/10/2015 [link] => https://www.example.com [description] => SimpleXMLElement Object ( ) )
没有包含 HTML 部分,因为我什至无法让循环正常工作。关于我遗漏或做错了什么的任何想法?谢谢
最佳答案
您还可以使用 XSLT 将 XML 转换为 HTML。
$baseurl = 'http://localhost/frontend/www/';
$url = $baseurl.'comment/rss/comments/?t='.time().'&l=4';
$xml = new DOMDocument();
$xml->loadXML(file_get_contents($url));
$xsl = new DOMDocument();
$xsl->load('feed-to-html-table.xsl');
$xsltp = new XSLTProcessor();
$xsltp->importStyleSheet($xsl);
echo $xsltp->transformToXML($xml);
feed-to-html-table.xsl
XSL 样式表可能是这样的:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/rss/channel">
<table>
<xsl:apply-templates select="item" />
</table>
</xsl:template>
<xsl:template match="item">
<tr>
<td><a href="{link}"><xsl:value-of select="title" /></a></td>
<td><img src="{image}" /></td>
<td><xsl:value-of select="date" /> <xsl:value-of select="time" /></td>
</tr>
</xsl:template>
</xsl:stylesheet>
关于php - 使用 PHP 将 XML 转换为 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33386434/