首页  >  文章  >  后端开发  >  php操作XML、读取数据和写入数据的实现代码

php操作XML、读取数据和写入数据的实现代码

高洛峰
高洛峰原创
2016-12-24 11:20:211749浏览

xml文件

<?xml version="1.0" encoding="utf-8"?>
  
<vip>
 <id>23</id>
 <username>开心的路飞</username>
 <sex>男</sex>
 <face>face/43.jpg</face>
 <email>123@qq.com</email>
 <qq>1212121212</qq>
</vip>


php解析XML获取标签中的值

/*
 * _get_xml 获取的XML文件
* @access public 表示函数对外公开
* @param $_xmlfile xml文件
* $_html 从XML中取出的数据数组
* */
function _get_xml($_xmlfile){
  $_html = array();
  if(file_exists($_xmlfile)){
    $_xml = file_get_contents($_xmlfile);
    preg_match_all(&#39;/<vip>(.*)<\/vip>/&#39;, $_xml,$_dom);   
    foreach($_dom[1] as $_value){
      preg_match_all(&#39;/<id>(.*)<\/id>/&#39;, $_value,$_id);
      preg_match_all(&#39;/<username>(.*)<\/username>/&#39;, $_value,$_username);
      preg_match_all(&#39;/<sex>(.*)<\/sex>/&#39;, $_value,$_sex);
      preg_match_all(&#39;/<face>(.*)<\/face>/&#39;, $_value,$_face);
      preg_match_all(&#39;/<email>(.*)<\/email>/&#39;, $_value,$_email);
      preg_match_all(&#39;/<qq>(.*)<\/qq>/&#39;, $_value,$_qq);
      $_html[&#39;id&#39;] = $_id[1][0];
      $_html[&#39;username&#39;] = $_username[1][0];
      $_html[&#39;sex&#39;] = $_sex[1][0];
      $_html[&#39;face&#39;] = $_face[1][0];
      $_html[&#39;email&#39;] = $_email[1][0];
      $_html[&#39;qq&#39;] = $_qq[1][0];
    }
  }else{
    _alert_back("文件不存在");
  }
  return $_html;
}

   

php向XML文件中写入数据

/*
 * _set_xml将信息写入XML文件
* @access public 表示函数对外公开
* @param $_xmlfile xml文件
* @param $_clean 要写入的信息的数组
* */
function _set_xml($_xmlfile,$_clean){
  $_fp = @fopen(&#39;newuser.xml&#39;,&#39;w&#39;);
  if(!$_fp){
    exit(&#39;系统错误,文件不存在!&#39;);
  }
  flock($_fp,LOCK_EX);
  $_string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "<vip>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "\t<id>{$_clean[&#39;id&#39;]}</id>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "\t<username>{$_clean[&#39;username&#39;]}</username>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "\t<sex>{$_clean[&#39;sex&#39;]}</sex>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "\t<face>{$_clean[&#39;face&#39;]}</face>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "\t<email>{$_clean[&#39;email&#39;]}</email>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "\t<qq>{$_clean[&#39;url&#39;]}</qq>\r\t";
  fwrite($_fp, $_string,strlen($_string));
  $_string = "</vip>";
  fwrite($_fp, $_string,strlen($_string));
  flock($_fp,LOCK_UN);
  fclose($_fp);
}

   

更多php操作XML、读取数据和写入数据的实现代码相关文章请关注PHP中文网!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn