遇到一个用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
- <?xml version="1.0" encoding="UTF-8"?>
- <xsl:stylesheet version="1.0"
- xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
- xmlns:php="http://php.net/xsl">
- <xsl:output method="html" encoding="utf-8" indent="yes"/>
- <xsl:template match="allusers">
- <html><body>
- <h2>Users</h2>
- <table>
- <xsl:for-each select="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 = new XSLTProcessor();
- $proc->registerPHPFunctions();
- $proc->importStyleSheet($xsldoc);
- echo $proc->transformToXML($xmldoc);
- ?>
collection.xml
- <?xml version="1.0"?>
- <collection>
- <cd>
- <title>Fight for your mind</title>
- <artist>Ben Harper</artist>
- <year>1995</year>
- </cd>
- <cd>
- <title>Electric Ladyland</title>
- <artist>Jimi Hendrix</artist>
- <year>1997</year>
- </cd>
- </collection>
- <?xml version="1.0"?>
- <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
- <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
- <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
- <xsl:template match="collection">
- Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection!
- <xsl:apply-templates/>
- </xsl:template>
- <xsl:template match="cd">
- <h1><xsl:value-of select="title"/></h1>
- <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
- <hr />
- </xsl:template>
- </xsl:stylesheet>
- <?php
- $xslDoc = new DOMDocument();
- $xslDoc->load("collection.xsl");
- $xmlDoc = new DOMDocument();
- $xmlDoc->load("collection.xml");
- $proc = new XSLTProcessor();
- $proc->importStylesheet($xslDoc);
- echo $proc->transformToXML($xmlDoc);
- ?>