XML----DOM ADD

前端之家收集整理的这篇文章主要介绍了XML----DOM ADD前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

students.xml

<?xml version="1.0" encoding="utf-8"?>
<students>
	<student>
		<name>小明</name>
		<age>10</age>
		<introduce>来自广东</introduce>
	</student>
	<student>
		<name>小花</name>
		<age>21</age>
		<introduce>来自北京</introduce>
	</student>

</students>


stu_add_dom.PHP

<?PHP

$xmldoc = new DOMDocument();	//1.创建DOMDocument对象
$xmldoc->load("students.xml");	//2.加载xml文件

//添加一个学生信息
$root = $xmldoc->getElementsByTagName("students")->item(0);    //取出根节点
$stu_node = $xmldoc->createElement("student");		//创建student节点


//创建属性节点
$stu_node->setAttribute("sex","female");


$stu_node_name = $xmldoc->createElement("name");	//创建name节点
$stu_node_name->nodeValue="小白";		//给name添加节点值
$stu_node->appendChild($stu_node_name);	//把name节点挂载到student节点下

$stu_node_age = $xmldoc->createElement("age");
$stu_node_age->nodeValue="20";
$stu_node->appendChild($stu_node_age);

$stu_node_introduce = $xmldoc->createElement("introduce");
$stu_node_introduce->nodeValue="来自上海";
$stu_node->appendChild($stu_node_introduce);

//把student节点$stu_node挂载到根节点下
$root->appendChild($stu_node);

//如果save是源文件名,则会对文件做更新处理
//如果save是新文件名,则会按文件名创建文件并保存
$xmldoc->save("students.xml");
?>

input:
<?xml version="1.0" encoding="utf-8"?>
<students>
	<student>
		<name>小明</name>
		<age>10</age>
		<introduce>来自广东</introduce>
	</student>
	<student>
		<name>小花</name>
		<age>21</age>
		<introduce>来自北京</introduce>
	</student>

<student sex="female"><name>小白</name><age>20</age><introduce>来自上海</introduce></student></students>
原文链接:https://www.f2er.com/xml/297221.html

猜你在找的XML相关文章