欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP SimpleXMLElement:XML文件解析和读写

程序员文章站 2022-03-19 20:30:48
...
PHP保存XML文件
$xml=new SimpleXMLElement(XML数据);
        $xml->asXML(文件名);

PHP读取XML文件

XXX= simplexml_load_file(文件名);


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

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

//创建XML文件publicfunctionwriteTest()
{$_data = 
ABC老四30ReminderDon't forget the meeting!

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"
"
; } //测试 用数组下标读取数组某一项publicfunctionreaddata1() {$this->readFile(); echo"读取第[1]个data数据:"; echo$this->rxml->data[1] ."
"
; } //测试:读取2级XML节点publicfunctionreadfrom() {$this->readFile(); echo"读取from节点:"; echo$this->rxml->from->name .','; echo$this->rxml->from->arg."
"
; //读取name节点的fristname属性echo$this->rxml->from->name['fristname']."
"
; } } $tmp = new XmlTest(); $tmp->writeTest(); $tmp->readdata(); $tmp->readdata1(); $tmp->readfrom(); ?>

浏览器打印:

[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"
"
; } publicfunctionreaddata1_xpath() {$this->readFile(); $data1 = $this->rxml->xpath('/root/data'); echo"读取第[1]个data数据:"; echo$data1[1] ."
"
; } 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]."
"
; //读取name节点的fristname属性echo$name[0]['fristname']."
"
; }
$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教程有兴趣的朋友有所帮助。