PHP讀寫XML檔案(一)

來源:互聯網
上載者:User

標籤: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檔案(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.