php xml文件操作代码(一)

2015-01-24信息快讯网

创建SimpleXML对象 学习操作xml的朋友可以看看。

example.xml文件:
<?php 
$xml = simplexml_load_file('example.xml'); //创建SimpleXML对象 
print_r($xml); //输出XML 
?> 

<?xml version='1.0'?> 
<departs> 
<depart> 
<name>production support</name> 
<employees> 
<employee> 
<serial_no>100001</serial_no> 
<name>Simon</name> 
<age>24</age> 
<birthday>1982-11-06</birthday> 
<salary>5000.00</salary> 
<bonus>1000.00</bonus> 
</employee> 
<employee> 
<serial_no>100002</serial_no> 
<name>Elaine</name> 
<age>24</age> 
<birthday>1982-01-01</birthday> 
<salary>6000.00</salary> 
<bonus>2000.00</bonus> 
</employee> 
</employees> 
</depart> 
<depart> 
<name>testing center</name> 
<employees> 
<employee> 
<serial_no>110001</serial_no> 
<name>Helen</name> 
<age>23</age> 
<birthday>1983-07-21</birthday> 
<salary>5000.00</salary> 
<bonus>1000.00</bonus> 
</employee> 
</employees> 
</depart> 
</departs>

<?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); //关闭文件 
?>
©2014-2024 dbsqp.com