PHP怎么读写xml文件?

PHPz
Release: 2020-09-04 14:28:41
Original
1388 people have browsed it

PHP怎么读写xml文件?

PHP读写XML的方法:

PHP对XML文件进行读写操作的方法一共有四种,分别是:字符串方式直接读写、DOMDocument读写、XMLWrite写和XMLReader读、SimpleXML读写,本文将依次对这四种方法进行介绍。

介绍之前首先对本文例子使用的数据和文件进行说明。本文写XML文件的例子都是从MySQL中读取数据然后写入到XML文件中,读XML文件的例子都是从XML文件中读取数据后组装成数组的格式,数组中每个元素对应数据库中的一条记录。

MySQL中的数据:

1 (1).png

XML文件:

<?xml version="1.0" encoding="utf8"?>
<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>
Copy after login

读取XML文件后组装成的数据格式:

2 (1).png

下面的例子使用的数据、文件都是以上所列数据、文件,介绍各个方法时不再赘述,直接贴代码。

一、PHP字符串方式读写XML文件:

1、字符串方式写XML文件:

<?php
/**
* function:使用字符串方式写XML文件
* author:JetWu
* date:2016.12.03
**/
$mysqli = mysqli_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;123456&#39;, &#39;wjt&#39;);
if(mysqli_connect_errno()) die(&#39;database connect fail:&#39; . mysqli_connect_error());
 
$sql = &#39;select * from study order by starttime&#39;;
$res = mysqli_query($mysqli, $sql);
$study = array();
while($row = mysqli_fetch_array($res)) {
    $study[] = $row;
}
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
 
$str = "<studentcareer>\n";
foreach($study as $v) {
    $str .= "\t<period>\n";
    foreach($xmlTag as $x) {
        $str .= "\t\t<".$x.">" . $v[$x] . "</".$x.">\n";
    }
    $str .= "\t</period>\n";
}
$str .= &#39;</studentcareer>&#39;;
 
$file = &#39;./write_str.xml&#39;;
file_put_contents($file, $str);
Copy after login

2、字符串方式读XML文件:

<?php
/**
* function:使用字符串方式读XML文件
* author:JetWu
* date:2016.12.03
**/
$file = &#39;./write_str.xml&#39;;
$con = file_get_contents($file);
 
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
 
$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].&#39;>&#39;, $v);
        $v = substr($a[1], 0, strlen($a[1])-2);
        $data[$k][$xmlTag[$key]] = $v;
    }
}
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($data);
Copy after login

二、DOMDocument读写XML文件

1、DOMDocument写XML文件:

<?php
/**
* function:DOMDocument写XML文件
* author:JetWu
* date:2016.12.03
**/
$mysqli = mysqli_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;123456&#39;, &#39;wjt&#39;);
if(mysqli_connect_errno()) die(&#39;database connect fail:&#39; . mysqli_connect_error());
 
$sql = &#39;select * from study order by starttime&#39;;
$res = mysqli_query($mysqli, $sql);
$study = array();
while($row = mysqli_fetch_array($res)) {
    $study[] = $row;
}
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
 
$dom = new DOMDocument(&#39;1.0&#39;, &#39;utf8&#39;);
$dom->formatOutput = true;
$studentcareer = $dom->createElement(&#39;studentcareer&#39;);
$dom->appendChild($studentcareer);
foreach($study as $s) {
    $period = $dom->createElement(&#39;period&#39;);
    $studentcareer->appendChild($period);
    foreach($xmlTag as $x) {
        $element = $dom->createElement($x);
        $period->appendChild($element);
        $text = $dom->createTextNode($s[$x]);
        $element->appendChild($text);
    }
}
$dom->save(&#39;./write_dom.xml&#39;);
Copy after login

2、DOMDocument读XML文件:

<?php
/**
* function:DOMDocument读XML文件
* author:JetWu
* date:2016.12.03
**/
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
$dom = new DOMDocument();
$dom->load(&#39;./write_dom.xml&#39;);
$periods = $dom->getElementsByTagName(&#39;period&#39;);
$study = array();
foreach($periods as $k => $p) {
    foreach($xmlTag as $x) {
        $node = $p->getElementsByTagName($x);
        $study[$k][$x] = $node->item(0)->nodeValue;
    }
}
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($study);
Copy after login

三、XMLWriter和XMLReader读写XML文件

1、XMLWriter写XML文件:

<?php
/**
* function:XMLWriter写XML文件
* author:JetWu
* date:2016.12.03
**/
$mysqli = mysqli_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;123456&#39;, &#39;wjt&#39;);
if(mysqli_connect_errno()) die(&#39;database connect fail:&#39; . mysqli_connect_error());
 
$sql = &#39;select * from study order by starttime&#39;;
$res = mysqli_query($mysqli, $sql);
$study = array();
while($row = mysqli_fetch_array($res)) {
    $study[] = $row;
}
 
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
 
$xml = new XMLWriter();
$xml->openUri(&#39;./write_WR.xml&#39;);
$xml->setIndentString(&#39;  &#39;);//设置缩进格式化使用的符号
$xml->setIndent(true);
$xml->startDocument(&#39;1.0&#39;, &#39;utf8&#39;);
$xml->startElement(&#39;studentcareer&#39;);
foreach($study as $s) {
    $xml->startElement(&#39;period&#39;);
    foreach($xmlTag as $x) {
        $xml->startElement($x);
        $xml->text($s[$x]);
        $xml->endElement();
    }
    $xml->endElement();
}
$xml->endElement();
$xml->endDocument();
$xml->flush();
Copy after login

2、XMLReader读XML文件:

<?php
/**
* function:XMLReader读XML文件
* author:JetWu
* date:2016.12.03
**/
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
$xml = new XMLReader();
$xml->open(&#39;./write_WR.xml&#39;);
$study = array();
$count = 0;//记录数:方便组装数据
$name = &#39;&#39;;
while($xml->read()) {
    $n = $xml->name;
    if($xml->nodeType == XMLReader::ELEMENT) {
        if($n == &#39;period&#39;) {//开始下一条记录的读取
            $count ++;
        } else if(in_array($n, $xmlTag)) {//记录需要获取文本值的标签名
            $name = $n;
        }
    } else if($xml->nodeType == XMLReader::TEXT) {
        if(in_array($name, $xmlTag)) {
            $study[$count][$name] = $xml->value;
        }
    }
}
$xml->close();
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($study);
Copy after login

四、SimpleXML读写XML文件

1、SimpleXML写XML文件:

<?php
/**
* function:SimpleXML写XML文件
* author:JetWu
* date:2016.12.03
**/
$mysqli = mysqli_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;123456&#39;, &#39;wjt&#39;);
if(mysqli_connect_errno()) die(&#39;database connect fail:&#39; . mysqli_connect_error());
 
$sql = &#39;select * from study order by starttime&#39;;
$res = mysqli_query($mysqli, $sql);
$study = array();
while($row = mysqli_fetch_array($res)) {
    $study[] = $row;
}
 
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
$xml = new SimpleXMLElement(&#39;<?xml version="1.0" encoding="UTF-8"?><studentcareer />&#39;);
foreach($study as $s) {
    $period = $xml->addChild(&#39;period&#39;);
    foreach($xmlTag as $x) {
        $period->addChild($x, $s[$x]);
    }
}
$xml->asXml(&#39;./write_sim.xml&#39;);//输出XML文件(没有格式化)
Copy after login

2、SimpleXML读XML文件:

<?php
/**
* function:SimpleXML读XML文件
* author:JetWu
* date:2016.12.03
**/
//XML标签配置
$xmlTag = array(
    &#39;starttime&#39;,
    &#39;endtime&#39;,
    &#39;school&#39;
);
$study = array();
$xml = simplexml_load_file(&#39;./write_sim.xml&#39;);
foreach($xml->children() as $period) {
    $study[] = get_object_vars($period);//获取对象全部属性,返回数组
}
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($study);
Copy after login

总结:这四种方法中,字符串的方式是最原始的方法。SimpleXML和DOM扩展是属于基于树的解析器,把整个文档存储为树的数据结构中,需要把整个文档都加载到内存中才能工作,所以当处理大型XML文档的时候,性能会剧减。XMLReader则是属于基于流的解析器,它不会一次把整个文档加载到内存中,而是每次分别读取其中的一个节点并允许实时与之交互,这种方式效率高,而且占内存少。

更多相关知识,请访问 PHP中文网!!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template