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

基于PHP对XML的操作详解

程序员文章站 2022-12-26 21:53:00

<?php 

    $xml = simplexml_load_file('example.xml');              //创建simplexml对象  
    var_dump($xml);                                                             //输出xml  
?> 

<?php 
    $xml = simplexml_load_file('example.xml');          //读取xml文件  
    foreach($xml->depart as $a)                                    //循环读取xml数据中的每一个depart标签  
    { 
        echo "$a->name <br>";                                       //输出其中的name属性  
    } 
?> 

<?php 
    $xml = simplexml_load_file('example.xml');          //读取xml文件  
    echo $xml->depart->name[0];                                  //输出节点  
?> 

<?php 
    $xml = simplexml_load_file('example.xml'); 
    foreach ($xml->depart->children() as $depart)             //循环读取depart标签下的子标签  
    { 
       var_dump($depart);                                                        //输出标签的xml数据  
    } 
?> 

<?php 
    $xml = simplexml_load_file('example.xml');                      //读取xml文件  
    $result = $xml->xpath('/departs/depart/employees/employee/name');        //定义节点  
    var_dump($result);                                          //输出节点  
?> 

<?php 
    $xml = simplexml_load_file('example.xml');              //读取xml  
    $xml->depart->name[0] = "human resource";         //修改节点  
?> 

<?php 
    $xml = simplexml_load_file('example.xml');              //读取xml数据  
    echo $xml->asxml();                                                     //标准化xml数据  
?> 

<?php 
    $xml = simplexml_load_file('example.xml');              //读取xml数据  
    $newxml = $xml->asxml();                         //标准化xml数据  
    $fp = fopen("newxml.xml", "w");                  //打开要写入xml数据的文件  
    fwrite($fp, $newxml);                                    //写入xml数据  
    fclose($fp);                                                     //关闭文件  
?>