把XML数据转换成为HTML的问题

遇到一个用PHP把XML中的数据转换成HTML的问题,只是知道方案可是一让手写就写不出来了,真是的.特意从PHP手册取一个放在这里,提个醒,以后这方面还要加强一下
如果对xsl的语法不了解的话可以去 http://www.w3school.com.cn/xsl/xsl_languages.asp 补习一下,这个网站有很多W3C方面的知识
  1. <?php
  2. $xml = <<<EOB
  3. <allusers>
  4.  <user>
  5.   <uid>bob</uid>
  6.  </user>
  7.  <user>
  8.   <uid>joe</uid>
  9.  </user>
  10. </allusers>
  11. EOB;
  12. $xsl = <<<EOB
  13. <?xml version="1.0" encoding="UTF-8"?>
  14. <xsl:stylesheet version="1.0" 
  15.      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  16.      xmlns:php="http://php.net/xsl">
  17. <xsl:output method="html" encoding="utf-8" indent="yes"/>
  18.  <xsl:template match="allusers">
  19.   <html><body>
  20.     <h2>Users</h2>
  21.     <table>
  22.     <xsl:for-each select="user">
  23.       <tr>
  24.         <td>
  25.         <xsl:value-of
  26.              select="php:function('ucfirst',string(uid))"/>
  27.         </td>
  28.       </tr>
  29.     </xsl:for-each>
  30.     </table>
  31.    </body>
  32.   </html>
  33.  </xsl:template>
  34. </xsl:stylesheet>
  35. EOB;
  36. $xmldoc = DOMDocument::loadXML($xml);
  37. $xsldoc = DOMDocument::loadXML($xsl);
  38. $proc = new XSLTProcessor();
  39. $proc->registerPHPFunctions();
  40. $proc->importStyleSheet($xsldoc);
  41. echo $proc->transformToXML($xmldoc);
  42. ?> 
例子二:
collection.xml
  1. <?xml version="1.0"?>
  2. <collection>
  3.  <cd>
  4.   <title>Fight for your mind</title>
  5.   <artist>Ben Harper</artist>
  6.   <year>1995</year>
  7.  </cd>
  8.  <cd>
  9.   <title>Electric Ladyland</title>
  10.   <artist>Jimi Hendrix</artist>
  11.   <year>1997</year>
  12.  </cd>
  13. </collection>
collection.xsl
  1. <?xml version="1.0"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.  <xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
  4.  <xsl:output method="html" encoding="iso-8859-1" indent="no"/>
  5.  <xsl:template match="collection">
  6.   Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection! 
  7.   <xsl:apply-templates/>
  8.  </xsl:template>
  9.  <xsl:template match="cd">
  10.   <h1><xsl:value-of select="title"/></h1>
  11.   <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
  12.   <hr />
  13.  </xsl:template>
  14. </xsl:stylesheet>
transformToXML.php
  1. <?php
  2.    $xslDoc = new DOMDocument();
  3.    $xslDoc->load("collection.xsl");
  4.    $xmlDoc = new DOMDocument();
  5.    $xmlDoc->load("collection.xml");
  6.    $proc = new XSLTProcessor();
  7.    $proc->importStylesheet($xslDoc);
  8.    echo $proc->transformToXML($xmlDoc);
  9. ?>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值