用PHP实现动态产生XML文件以及从XML文件中抽取数据转化成HTML的小程序,不用DOM的

这个东东搞了我一天。。。可是到最后发现却无法实现自己想像中的那种效果。。。真是可惜。。。看来PHP对XML还需要加强。。。如果哪位对此有研究。欢迎来信探讨。。。

首先建表:
CREATE TABLE books (
   bookid int(4) NOT NULL auto_increment,
   bookname varchar(100) NOT NULL,
   bookauth varchar(50) NOT NULL,
   bookpublisher varchar(50) NOT NULL,
   bookpubdate datetime NOT NULL,
   bookurl varchar(50) NOT NULL,
   KEY bookid (bookid),
);

然后。。。这段是从MYSQL里取数据转化成XML的源代码:
<?
$connect_id=mysql_connect("localhost","root","");
mysql_select_db("bbs",$connect_id);
$query="select * from books order by bookid";
$rs=mysql_query($query,$connect_id);
$numfields=mysql_num_fields($rs);
$xmlfile="<?xml version=\"1.0\" encoding=\"GB2312\"?>\n";
$xmlfile.="<books>\n";

while($row=mysql_fetch_array($rs)){
    for($i=0;$i<$numfields;$i++){
        $fieldname=mysql_field_name($rs,$i);
        $xmlfile.="<" . $fieldname . ">" . $row[$i] . "</" . $fieldname . ">\n";
    }
}
mysql_free_result($rs);
mysql_close($connect_id);
$xmlfile.="</books>\n";
$fp=fopen("xmldoc/xmldoc.xml","w");
if(fwrite($fp,$xmlfile)){
    echo "写入文件成功!";
}
else{
    echo "写入文件失败!";
}
?>

这段是从XML里取数据转化成HTML的源代码。。。
<?
class xml{
    var $parser;

    function xml(){
        $this->parser = xml_parser_create();
        xml_set_object($this->parser,&$this);
        xml_set_element_handler($this->parser,"tag_on","tag_off");
        xml_set_character_data_handler($this->parser,"cdata");
    }
    
    function parse($data){
        xml_parse($this->parser,$data);
    }
    
    function tag_on($parser,$tag,$attributes){
        if(xml_get_current_line_number($parser)==2){
            echo "<tr><td colspan=\"2\" align=\"center\">" . $tag . "</td>";
        }
        else{
            switch ((xml_get_current_line_number($parser)-2)%6){
                case 0:
                    echo "<tr><td>下载<td>";
                    break;
                case 1:
                    echo "<tr><td>ID号<td>";
                    break;
                case 2:
                    echo "<tr><td>书名<td>";
                    break;
                case 3:
                    echo "<tr><td>作者<td>";
                    break;
                case 4:
                    echo "<tr><td>出版社<td>";
                    break;
                case 5:
                    echo "<tr><td>出版日期<td>";
                    break;
            }
        }
    }
    
    function cdata($parser,$cdata){
        echo $cdata;
    }
    
    function tag_off($parser,$tag){
        echo "\n";
    }
}

$xml_parser = new xml();
$xmlfilename="xmldoc/xmldoc.xml";
$fp=fopen($xmlfilename,"r");
$xmldata=fread($fp,filesize($xmlfilename));
?>
<html><head><title>图书信息</title></head>
<body>
<table border="0" cellspacing="1" cellpadding="2" width="80%" bgcolor="#b0d8fF" align="center">
<?
$xml_parser->parse($xmldata);
?>
</table>

其实你们应该看得出。。这个例子是个失败的东东。。。因为效果不大。。根本不能得到自己想要的东东。。。唉。。。苦。。。。
300*300
  • 没有相关文章
  • 没有评论
 文章首页关于迷茫时代关于我写意人生
版权所有:迷茫时代 All rights reserved   
执行时间:0.00533 秒