標籤:substr mysql 2.0 四種 local 資料庫 [] erro 技術分享
PHP讀寫XML檔案的方法有四種,從本文開始將連續使用四篇博文來分別介紹這四種方法。本文介紹的是第一種方法:
使用字串操作的方式來對XML檔案進行讀寫操作。
一、PHP字串方式寫XML檔案:
首先介紹PHP使用字串方式寫XML檔案。本例將讀取資料庫中的資料,輸出為XML檔案。
資料庫資料如下:
讀取資料並寫入XML檔案代碼:
<?php/*** function:使用字串方式寫XML檔案* author:JetWu* date:2016.12.03**/$mysqli = mysqli_connect(‘localhost‘, ‘root‘, ‘123456‘, ‘wjt‘);if(mysqli_connect_errno()) die(‘database connect fail:‘ . mysqli_connect_error());$sql = ‘select * from study order by starttime‘;$res = mysqli_query($mysqli, $sql);$study = array();while($row = mysqli_fetch_array($res)) {$study[] = $row;}$str = "<studentcareer>\n";foreach($study as $v) {$str .= "\t<period>\n";$str .= "\t\t<starttime>" . $v[‘starttime‘] . "</starttime>\n";$str .= "\t\t<endtime>" . $v[‘endtime‘] . "</endtime>\n";$str .= "\t\t<school>" . $v[‘school‘] . "</school>\n";$str .= "\t</period>\n";}$str .= ‘</studentcareer>‘;$file = ‘./write_str.xml‘;file_put_contents($file, $str);echo ‘success!‘;
輸出XML檔案:
<studentcareer><period><starttime>2000</starttime><endtime>2002</endtime><school>培新小學</school></period><period><starttime>2002</starttime><endtime>2006</endtime><school>覽表東陽學校</school></period><period><starttime>2006</starttime><endtime>2009</endtime><school>惠來慈雲實驗中學</school></period><period><starttime>2009</starttime><endtime>2012</endtime><school>惠來一中</school></period><period><starttime>2012</starttime><endtime>2016</endtime><school>華南師範大學</school></period></studentcareer>
二、PHP字串方式讀XML檔案
接下來介紹使用字串方式讀取上一步產生的XML檔案,並提取、組裝資料。
代碼:
<?php/*** function:使用字串方式寫XML檔案* author:JetWu* date:2016.12.03**/$file = ‘./write_str.xml‘;$con = file_get_contents($file);//XML標籤配置$xmlTag = array(‘starttime‘,‘endtime‘,‘school‘);$arr = array();foreach($xmlTag as $x) {preg_match_all("/<".$x.">.*<\/".$x.">/", $con, $temp);$arr[] = $temp[0];}//去除XML標籤並組裝資料$data = array();foreach($arr as $key => $value) {foreach($value as $k => $v) {$a = explode($xmlTag[$key].‘>‘, $v);$v = substr($a[1], 0, strlen($a[1])-2);$data[$k][$xmlTag[$key]] = $v;}}echo ‘<pre>‘;print_r($data);
讀取列印後的資料格式:
讀取組裝後的數組中每個元素便是對應資料庫中的每一條記錄,可以很方便地將讀取後的資料插入到資料庫中。
PHP讀寫XML檔案(一)