PHP读取与解析XML的方法汇总——转载

PHP读取与解析XML的方法汇总

2010-12-10

首先要说下编码问题,如果XML文件与页面文件编码不一致,那么乱码会产生。解决中文乱码问题可以输出时用以下语句:echo iconv("UTF-8","GBK",$Song_Url);

PHP网页的编码

php文件本身的编码与网页的编码应匹配, 如果欲使用gb2312编码,那么php要输出头:header("Content-Type: text/html; charset=gb2312"),静态页面添加<meta http-equiv="Content-Type" content="text/html; charset=gb2312">,所有文件的编码格式为ANSI,可用记事本打开,另存为选择编码为ANSI,覆盖源文件。

如果想使用utf-8编码,那么php要输出头:header("Content-Type: text/html; charset=utf-8"),静态页面添加<meta http-equiv="Content-Type" content="text/html; charset=utf-8">,所有文件的编码格式为utf-8。保存为utf-8可能会有点麻烦,一般utf-8文件开头会有BOM,如果使用 session就会出问题,可用editplus来保存,在editplus中,工具->参数选择->文件->UTF-8签名,选择总是删除,再保存就可以去掉BOM信息了。

php本身不是Unicode的,所有substr之类的函数得改成mb_substr(需要装mbstring扩展);或者用iconv转码。

PHP与Mysql的数据交互PHP与数据库的编码应一致

修改mysql配置文件my.ini或my.cnf,mysql最好用utf8编码[mysql]

1 default-character-set=utf8
2 [mysqld]
3 default-character-set=utf8
4 default-storage-engine=MyISAM
5 在[mysqld]下加入:
6 default-collation=utf8_bin
7 init_connect='SET NAMES utf8'

在需要做数据库操作的php程序前加mysql_query("set names '编码'");,编码和php编码一致,如果php编码是gb2312那mysql编码就是gb2312,如果是utf-8那mysql 编码就是utf8,这样插入或检索数据时就不会出现乱码了。

PHP与操作系统相关

Windows和Linux的编码是不一样的,在Windows环境下,调用PHP的函数时参数如果是utf-8编码会出现错误,比如 move_uploaded_file()、filesize()、readfile()等,这些函数在处理上传、下载时经常会用到,调用时可能会出现下面的错误:

1 Warning: move_uploaded_file()[function.move-uploaded-file]:failed to open stream: Invalid argument in ...
2 Warning: move_uploaded_file()[function.move-uploaded-file]:Unable to move '' to '' in ...
3 Warning: filesize() [function.filesize]: stat failed for ... in ...
4 Warning: readfile() [function.readfile]: failed to open stream: Invalid argument in ..

在Linux环境下用gb2312编码虽然不会出现这些错误,但保存后的文件名出现乱码导致无法读取文件,这时可先将参数转换成操作系统识别的编码,编码转换可用mb_convert_encoding(字符串,新编码,原编码)或iconv(原编码,新编码,字符串),这样处理后保存的文件名就不会出现乱码,也可以正常读取文件,实现中文名称文件的上传、下载。

其实还有更好的解决方法,彻底与系统脱离,也就不用考虑系统是何编码。可以生成一个只有字母和数字的序列作为文件名,而将原来带有中文的名字保存在数据库中,这样调用move_uploaded_file()就不会出现问题,下载的时候只需将文件名改为原来带有中文的名字。实现下载的代码如下:

1 header("Pragma: public");
2 header("Expires: 0");
3 header("Cache-Component: must-revalidate, post-check=0, pre-check=0");
4 header("Content-type: $file_type");
5 header("Content-Length: $file_size");
6 header("Content-Disposition: attachment; filename=\"$file_name\"");
7 header("Content-Transfer-Encoding: binary");
8 readfile($file_path); 

$file_type是文件的类型,$file_name是原来的名字,$file_path是保存在服务上文件的地址。

book.xml

01 <books>
02     <book>
03         <author>Jack Herrington</author>
04         <title>PHP Hacks</title>
05         <publisher>O'Reilly</publisher>
06     </book>
07     <book>
08         <author>Jack Herrington</author>
09         <title>Podcasting Hacks</title>
10         <publisher>O'Reilly</publisher>
11     </book>
12 </books>

使用 DOM 库读取 XML:

01 <?php
02 $doc new DOMDocument();
03 $doc->load( 'books.xml' );
04  
05 $books $doc->getElementsByTagName( "book" );
06 foreach$books as $book )
07 {
08     $authors $book->getElementsByTagName( "author" );
09     $author $authors->item(0)->nodeValue;
10  
11     $publishers $book->getElementsByTagName( "publisher" );
12     $publisher $publishers->item(0)->nodeValue;
13  
14     $titles $book->getElementsByTagName( "title" );
15     $title $titles->item(0)->nodeValue;
16  
17     echo "$title - $author - $publisher\n";
18 }
19 ?>

用 SAX 解析器读取 XML:

01 <?php
02 $g_books array();
03 $g_elem = null;
04  
05 function startElement( $parser$name$attrs )
06 {
07 global $g_books$g_elem;
08 if $name == 'BOOK' $g_books []= array();
09 $g_elem $name;
10 }
11  
12 function endElement( $parser$name )
13 {
14 global $g_elem;
15 $g_elem = null;
16 }
17  
18 function textData( $parser$text )
19 {
20 global $g_books$g_elem;
21 if $g_elem == 'AUTHOR' ||
22 $g_elem == 'PUBLISHER' ||
23 $g_elem == 'TITLE' )
24 {
25 $g_bookscount$g_books ) - 1 ][ $g_elem ] = $text;
26 }
27 }
28  
29 $parser = xml_parser_create();
30  
31 xml_set_element_handler( $parser"startElement""endElement" );
32 xml_set_character_data_handler( $parser"textData" );
33  
34 $f fopen'books.xml''r' );
35  
36 while$data fread$f, 4096 ) )
37 {
38 xml_parse( $parser$data );
39 }
40  
41 xml_parser_free( $parser );
42  
43 foreach$g_books as $book )
44 {
45 echo $book['TITLE']." - ".$book['AUTHOR']." - ";
46 echo $book['PUBLISHER']."\n";
47 }
48 ?>

用正则表达式解析 XML:

01 <?php
02 $xml "";
03 $f fopen'books.xml''r' );
04 while$data fread$f, 4096 ) ) { $xml .= $data; }
05 fclose( $f );
06  
07 preg_match_all( "/\<book\>(.*?)\<\/book\>/s",
08 $xml$bookblocks );
09  
10 foreach$bookblocks[1] as $block )
11 {
12 preg_match_all( "/\<author\>(.*?)\<\/author\>/",
13 $block$author );
14 preg_match_all( "/\<title\>(.*?)\<\/title\>/",
15 $block$title );
16 preg_match_all( "/\<publisher\>(.*?)\<\/publisher\>/",
17 $block$publisher );
18 echo$title[1][0]." - ".$author[1][0]." - ".
19 $publisher[1][0]."\n" );
20 }
21 ?>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值