PHP SimpleXMLElement:XML文件解析和读写

时间:2022-10-20 19:35:58

PHP保存XML文件


$xml = new SimpleXMLElement(XML数据);
$xml->asXML(文件名);

PHP读取XML文件

XXX= simplexml_load_file(文件名);




1.使用面向对象方式访问XML

<?php

class XmlTest
{


private $filename = "a.xml";
private $isreading=false;
private $rxml;

//创建XML文件
public function writeTest()
{

$_data = <<<data
<?xml version="1.0" encoding="UTF-8"?>
<root>
<data>A</data>
<data>B</data>
<data>C</data>
<from>
<name fristname='陈'>老四</name>
<arg>30</arg>
</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</root>
data;

$xml = new SimpleXMLElement($_data);
$xml->asXML($this->filename);
}
//读取文件
private function readFile()
{

if(!$this->isreading)
{
$this->rxml= simplexml_load_file($this->filename);
$this->isreading=true;
}
}
//测试:遍历某一数组
public function readdata()
{


$this->readFile();
foreach ($this->rxml->data as $x) {
echo "[".$x."]";

}
echo "<br>";
}
//测试 用数组下标读取数组某一项
public function readdata1()
{

$this->readFile();
echo "读取第[1]个data数据:";
echo $this->rxml->data[1] ."<br>";
}
//测试:读取2级XML节点
public function readfrom()
{

$this->readFile();
echo "读取from节点:";
echo $this->rxml->from->name .',';
echo $this->rxml->from->arg."<br>";
//读取name节点的fristname属性
echo $this->rxml->from->name['fristname']."<br>";
}
}


$tmp = new XmlTest();
$tmp->writeTest();
$tmp->readdata();
$tmp->readdata1();
$tmp->readfrom();

?>

浏览器打印:

[A][B][C]
读取第[1]个data数据:B
读取from数据:老四,30






2.使用xpath访问XML., 用路径获取节点,区别:获取的节点都以数组返回,因此用数组下标访问

 public  function readdata_xpath() {
$this->readFile();
$data= $this->rxml->xpath('/root/data');
foreach ($data as $x) {
echo "[".$x."]";

}
echo "<br>";
}
public function readdata1_xpath()
{

$this->readFile();
$data1 = $this->rxml->xpath('/root/data');
echo "读取第[1]个data数据:";
echo $data1[1] ."<br>";
}
public function readfrom_xpath()
{

$this->readFile();
$name= $this->rxml->xpath('/root/from/name');
$arg= $this->rxml->xpath('/root/from/arg');
echo "读取from数据:";
echo $name[0] .',';
echo $arg[0]."<br>";
//读取name节点的fristname属性
echo $name[0]['fristname']."<br>";
}
$tmp->readdata_xpath();
$tmp->readdata1_xpath();
$tmp->readfrom_xpath();

******************
浏览器打印:
[A][B][C]
读取第[1]个data数据:B
读取from数据:老四,30