Heim  >  Artikel  >  Backend-Entwicklung  >  PHP正则表达式读取xml数据的代码举例

PHP正则表达式读取xml数据的代码举例

WBOY
WBOYOriginal
2016-07-25 08:59:20780Durchsuche
  1. 张映
  2. 28
  3. tank
  4. 28
复制代码

2、php处理文件,rexml.php

  1. /***
  2. @ 使用正则表达式读取xml文件
  3. @ Recoded By Androidyue
  4. @ site bbs.it-home.org
  5. ***/
  6. $xml = "";
  7. //只读模式打开所读取的文件
  8. $f = fopen('person.xml', 'r');
  9. //格式化获取读取的数据
  10. while( $data = fread( $f, 4096 ) ) {
  11. $xml .= $data;
  12. }
  13. //关闭一个已打开的文件指针
  14. fclose( $f );
  15. // 上面读取数据
  16. preg_match_all( "//(.*?)//humans/>/s", $xml, $humans ); //匹配最外层标签里面的内容
  17. //格式化数据
  18. foreach( $humans[1] as $k=>$human ){
  19. preg_match_all( "//(.*?)//name/>/", $human, $name ); //匹配出名字
  20. preg_match_all( "//(.*?)//sex/>/", $human, $sex ); //匹配出性别
  21. preg_match_all( "//(.*?)//old/>/", $human, $old ); //匹配出年龄
  22. }
  23. //处理结果数据
  24. foreach($name[1] as $key=>$val){
  25. echo $val." - ".$sex[$key][1]." - ".$old[$key][1]."
    " ;
  26. }
  27. ?>
复制代码

注意: 两个文件的编码格式,请保持一致,最好都设成UTF8的字符集,以免出现莫名的错误。



Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn