PHP SimpleXMLElement:XML文件解析和读写

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 
陈
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值