php - 使用 PHP 将 XML 转换为 HTML 表格

标签 php html xml yii

我正在尝试使用 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/

相关文章:

php - 无法从 PHP 运行 python

ruby-on-rails - 使用 Ruby on Rails (1.4GB) 解析非常大的 XML 文件——有没有比 SAXParser 更好的方法?

html - 在动画之间添加淡入淡出过渡

HTML5 文件 API - 切片与否?

html - 如果基于位置,则在 XSLT 中进行 HTML 输出

java - Web.Xml 文件丢失,项目正常工作

php - 表单提交后不支持将点 (.) 作为数组键字符

PHP MYSQL。如何根据另一个表中的2个不同ID从一个表中检索相同的数据

php - 使用PHP从HTML表单向MySQL插入数据报错

html - 水平对齐无序列表旁边的图像