php读写xml基于DOMDocument方法
1.读xml内容:
xml文件plays.xml文档结构:
<?xml version="1.0" encoding="UTF-8"?>
<Plays>
<play>
<title id="001">rabits</title>
<author>tom</author>
<date>2015.1.2</date>
<addr>Beijing Fengtai Juyuan</addr>
</play>
<play>
<title id="002">Mom's Love</title>
<author>Jim</author>
<date>2015.4.5</date>
<addr>Beijing haiding Juyuan</addr>
</play>
</Plays>
php xml文档读操作:
<?php
$doc = new DOMDocument();
$doc->load("plays.xml");
$plays = $doc->getElementsByTagName("play");
/**
* xml文档读取
*/
echo '<strong style="color:red">文档读取:</strong><br>';
foreach( $plays as $play )
{
$titles = $play->getElementsByTagName("title");
$title = $titles->item(0)->nodeValue;
$authors = $play->getElementsByTagName("author");
$author = $authors->item(0)->nodeValue;
echo "$title - $author <br>";
}
echo "<hr>";
/**
* xml文档属性读取
*/
echo '<strong style="color:red">文档属性读取:</strong><br>';
//首先建立一个DOMDocument对象
$xml = new DOMDocument();
//加载XML文件
$xml->load("plays.xml");
//获取所有的play标签
$play = $xml->getElementsByTagName("play");
foreach($play as $post)
{
$title = $post->getElementsByTagName("title");
echo "Title Id: " . $title->item(0)->attributes->item(0)->nodeValue ."<br />";
}
?>
表1 DOMDocument提供的读文档常用属性
2.xml文档写操作:
<?php
$local_array=array(
array("pid"=>"1", "name"=>"kitty","sex"=>"female"),
array("pid"=>"2", "name"=>"tom","sex"=>"male"),
);
//创建新的XML文档
$doc = new DomDocument('1.0');
// 创建根节点
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
foreach ($local_array as $a)
{
$table_id = 'person'; //元素名称
$occ = $doc -> createElement($table_id); //创建元素
$occ = $root -> appendChild($occ); //加入元素
$fieldname = 'pid'; //值
$child = $doc -> createElement($fieldname); //创建元素
$child = $occ -> appendChild($child); //加入值
$fieldvalue = $a["pid"];
$value = $doc -> createTextNode($fieldvalue);
$child -> appendChild($value);
$fieldname = 'name';
$child = $doc -> createElement($fieldname);
$child = $occ -> appendChild($child);
/**
* xml属性写入方法
*/
$child -> setAttribute('attr1', 'attr1Value');
$child -> setAttribute('attr2', 'attr2Value');
$fieldvalue = $a["name"];
$value = $doc -> createTextNode($fieldvalue);
$child -> appendChild($value);
$fieldname = 'sex';
$child = $doc -> createElement($fieldname);
$child = $occ -> appendChild($child);
$fieldvalue = $a["sex"];
$value = $doc -> createTextNode($fieldvalue);
$child -> appendChild($value);
}
$xml_string = $doc -> saveXML();
file_put_contents("file.xml", $xml_string);
echo $xml_string;
?>
程序生成的xml文档结构如下:
<?xml version="1.0"?>
<root>
<person>
<pid>1</pid>
<name attr1="attr1Value" attr2="attr2Value">kitty</name>
<sex>female</sex>
</person>
<person>
<pid>2</pid>
<name attr1="attr1Value" attr2="attr2Value">tom</name>
<sex>male</sex>
</person>
</root>
表2 DOMDocument提供的常用写方法