使用PHP的XML到HTML表

时间:2015-10-28 08:46:50

标签: php html xml yii

我正在尝试使用php

将下面的XML Feed转换为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部分因为我甚至无法使循环正常工作。关于我遗失或做错的任何想法?感谢

2 个答案:

答案 0 :(得分:0)

尝试使用XMLtoArray库(http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array/)代替。

它会在多维数组中转换你的xml,从那里循环遍历数组将是一件容易的工作

您更新的代码应该是

$baseurl = 'http://localhost/frontend/www/';
$url = $baseurl.'comment/rss/comments/?t='.time().'&l=4';
$xml = file_get_content($url,true);
$array = XML2Array::createArray($xml);

print_r($array);

答案 1 :(得分:0)

您还可以使用XSLT将XML转换为HTML。

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.provider "virtualbox" do |v|
    v.memory = 512
  end
  config.vm.box = "trusty64"
  config.vm.box_url = "https://cloud-images.ubuntu.com/vagrant/trusty/current/trusty-server-cloudimg-amd64-vagrant-disk1.box"
  config.vm.network "private_network", ip: "192.168.100.10"
  config.vm.synced_folder ".", "/opt/site"
  config.vm.hostname = "alexander"
end

$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); XSL样式表可能是这样的:

feed-to-html-table.xsl