PHP read and write XML files in four ways, from the beginning of this article will continue to use four blog respectively introduced the four methods. This article describes the first method:
Use string manipulation to read and write XML files.
One, PHP string way to write XML file:
The first step is to introduce PHP to write XML files using strings. This example reads the data from the database and outputs it as an XML file.
The database data is as follows:
Read the data and write the XML file code:
<?php/*** function: Write XML file using String * 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 S Tudy order by StartTime '; $res = Mysqli_query ($mysqli, $sql); $study = Array () and while ($row = Mysqli_fetch_array ($res)) {$stu Dy[] = $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! ';
Output XML file:
<studentcareer><period><starttime>2000</starttime><endtime>2002</endtime> <school> Pei Xin Primary School </school></period><period><starttime>2002</starttime>< endtime>2006</endtime><school> Table Dongyang School </school></period><period><starttime >2006</starttime><endtime>2009</endtime><school> Huilai ci Yun Experimental Middle school </school></period ><period><starttime>2009</starttime><endtime>2012</endtime><school> Huilai in one </school></period><period><starttime>2012</starttime><endtime>2016</ endtime><school> South China Normal University </school></period></studentcareer>
Second, PHP string way to read XML file
Next, you'll use a string to read the XML file generated in the previous step and extract and assemble the data.
Code:
<?php/*** function: Write XML file using String * author:jetwu* date:2016.12.03**/$file = './write_str.xml '; $con = file_get_ Contents ($file);//xml label configuration ' = ' Array (' starttime ', ' endtime ', ' School '); $arr = Array (); foreach ($xmlTag as $x) {Preg_ Match_all ("/<". $x. " >.*<\/". $x." >/", $con, $temp); $arr [] = $temp [0];} Remove the XML tag and assemble the data $data = Array (), foreach ($arr as $key + $value) {foreach ($value as $k + = $v) {$a = explode ($xmlTag [$ke Y]. ' > ', $v); $v = substr ($a [1], 0, strlen ($a [1])-2); $data [$k] [$XMLTAG [$key]] = $v;}} Echo ' <pre> ';p rint_r ($data);
Read the printed data format:
Each element in the assembled array is read each record in the corresponding database, and it is convenient to insert the read data into the database.
PHP read-write XML file (i)