php保存xml文件
$xml=new SimpleXMLElement(XML数据);
$xml->asXML(文件名);PHP读取XML文件
XXX= simplexml_load_file(文件名);
1.使用面向对象方式访问XML
<?phpclassXmlTest
{private$filename = "a.xml";
private$isreading=false;
private$rxml;
//创建XML文件publicfunctionwriteTest()
{$_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);
}
//读取文件privatefunctionreadFile()
{if(!$this->isreading)
{
$this->rxml= simplexml_load_file($this->filename);
$this->isreading=true;
}
}
//测试:遍历某一数组publicfunctionreaddata()
{$this->readFile();
foreach ($this->rxml->data as$x) {
echo"[".$x."]";
}
echo"<br>";
}
//测试 用数组下标读取数组某一项publicfunctionreaddata1()
{$this->readFile();
echo"读取第[1]个data数据:";
echo$this->rxml->data[1] ."<br>";
}
//测试:读取2级XML节点publicfunctionreadfrom()
{$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();
?>浏览器打印:
客客出品专业威客系统英文名称KPPW,也是keke produced professional witkey的缩写。KPPW是一款基于PHP+MYSQL技术构架的威客系统,积客客团队多年实践和对威客模式商业化运作的大量调查分析而精心策划研发,是您轻松搭建威客网站的首选利器。KPPW针对威客任务和商品交易模式进行了细致的分析,提供完善威客任务流程控制解决方案,并将逐步分享威客系统专业化应用作为我们的
立即学习“PHP免费学习笔记(深入)”;
[A][B][C] 读取第[1]个data数据:B 读取from数据:老四,30 陈
2.使用xpath访问XML., 用路径获取节点,区别:获取的节点都以数组返回,因此用数组下标访问
publicfunctionreaddata_xpath() {$this->readFile();
$data= $this->rxml->xpath('/root/data');
foreach ($dataas$x) {
echo"[".$x."]";
}
echo"<br>";
}
publicfunctionreaddata1_xpath()
{$this->readFile();
$data1 = $this->rxml->xpath('/root/data');
echo"读取第[1]个data数据:";
echo$data1[1] ."<br>";
}
publicfunctionreadfrom_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 陈
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });
以上就介绍了 PHP SimpleXMLElement:XML文件解析和读写,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。










