>  기사  >  백엔드 개발  >  XML을 작동하고, 데이터를 읽고, 데이터를 쓰는 PHP의 구현 코드

XML을 작동하고, 데이터를 읽고, 데이터를 쓰는 PHP의 구현 코드

高洛峰
高洛峰원래의
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을 운영하는 구현 코드, 데이터 읽기 및 쓰기에 대한 더 많은 기사를 보려면 다음을 참조하세요. Follow PHP 중국어 웹사이트를 방문해보세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.