遇到一个用PHP把XML中的数据转换成HTML的问题,只是知道方案可是一让手写就写不出来了,真是的.特意从PHP手册取一个放在这里,提个醒,以后这方面还要加强一下
如果对xsl的语法不了解的话可以去 http://www.w3school.com.cn/xsl/xsl_languages.asp 补习一下,这个网站有很多W3C方面的知识
例子二:
collection.xml
collection.xsl
transformToXML.php
如果对xsl的语法不了解的话可以去 http://www.w3school.com.cn/xsl/xsl_languages.asp 补习一下,这个网站有很多W3C方面的知识
- <?php
- $xml=<<<EOB
- <allusers>
- <user>
- <uid>bob</uid>
- </user>
- <user>
- <uid>joe</uid>
- </user>
- </allusers>
- EOB;
- $xsl=<<<EOB
- <?xmlversion="1.0"encoding="UTF-8"?>
- <xsl:stylesheetversion="1.0"
- xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
- xmlns:php="http://php.net/xsl">
- <xsl:outputmethod="html"encoding="utf-8"indent="yes"/>
- <xsl:templatematch="allusers">
- <html><body>
- <h2>Users</h2>
- <table>
- <xsl:for-eachselect="user">
- <tr>
- <td>
- <xsl:value-of
- select="php:function('ucfirst',string(uid))"/>
- </td>
- </tr>
- </xsl:for-each>
- </table>
- </body>
- </html>
- </xsl:template>
- </xsl:stylesheet>
- EOB;
- $xmldoc=DOMDocument::loadXML($xml);
- $xsldoc=DOMDocument::loadXML($xsl);
- $proc=newXSLTProcessor();
- $proc->registerPHPFunctions();
- $proc->importStyleSheet($xsldoc);
- echo$proc->transformToXML($xmldoc);
- ?>
collection.xml
- <?xmlversion="1.0"?>
- <collection>
- <cd>
- <title>Fightforyourmind</title>
- <artist>BenHarper</artist>
- <year>1995</year>
- </cd>
- <cd>
- <title>ElectricLadyland</title>
- <artist>JimiHendrix</artist>
- <year>1997</year>
- </cd>
- </collection>
- <?xmlversion="1.0"?>
- <xsl:stylesheetversion="1.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
- <xsl:paramname="owner"select="'NicolasEliaszewicz'"/>
- <xsl:outputmethod="html"encoding="iso-8859-1"indent="no"/>
- <xsl:templatematch="collection">
- Hey!Welcometo<xsl:value-ofselect="$owner"/>'ssweetCDcollection!
- <xsl:apply-templates/>
- </xsl:template>
- <xsl:templatematch="cd">
- <h1><xsl:value-ofselect="title"/></h1>
- <h2>by<xsl:value-ofselect="artist"/>-<xsl:value-ofselect="year"/></h2>
- <hr/>
- </xsl:template>
- </xsl:stylesheet>
- <?php
- $xslDoc=newDOMDocument();
- $xslDoc->load("collection.xsl");
- $xmlDoc=newDOMDocument();
- $xmlDoc->load("collection.xml");
- $proc=newXSLTProcessor();
- $proc->importStylesheet($xslDoc);
- echo$proc->transformToXML($xmlDoc);
- ?>