php 讀寫 xml

WBOY
發布: 2016-08-08 09:24:57
原創
1077 人瀏覽過

讀取xml資訊

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<class>
	<student>
		<name>张三</name>
		<age>23</age>
		<intro>努力学习</intro>
	</student>
	<student>
		<name>李四</name>
		<age>23</age>
		<intro>努力学习</intro>
	</student>
</class>
登入後複製
test.php
<?php
	$xmldoc = new DOMDocument();
	
	$xmldoc->load("test.xml");
	
	$stus = $xmldoc->getElementsByTagName("student");
	
	for($i=0;$i < $stus->length;$i++){
		
		$stu = $stus->item($i);
		echo getNodeVal($stu,"name")."--".getNodeVal($stu,"age")."--".
				getNodeVal($stu,"intro")."<br/>";
	}
	
	function getNodeVal(&$MyNode,$tagName){
		return $MyNode->getElementsByTagName($tagName)->item(0)->nodeValue;
	}
?>
登入後複製

寫xml:結點:

<span style="font-size:18px;"><?php
	$xmldoc = new DOMDocument("1.0","utf-8");
	
	$xmldoc->load("classes2.xml");
	
	//添加一个学生信息
	//创建学生结点
	$root = $xmldoc->getElementsByTagName("class")->item(0);
	$stu_node = $xmldoc->createElement("student");
	
	$stu_node->setAttribute("sex", "男");
	
	//创建名字结点并且挂载到学生结点下
	$stu_node_name=$xmldoc->createElement("name");
	$stu_node_name->nodeValue = "唐唐";
	$stu_node->appendChild($stu_node_name);
	
	$stu_node_age=$xmldoc->createElement("age");
	$stu_node_age->nodeValue = "24";
	$stu_node->appendChild($stu_node_age);
	
	$stu_node_intro=$xmldoc->createElement("intro");
	$stu_node_intro->nodeValue = "我是唐唐,我一直很努力";
	$stu_node->appendChild($stu_node_intro);
	
	//把学生结点挂载到根结点下
	$root->appendChild($stu_node);
	
	$xmldoc->save("new.xml");
?></span>
登入後複製

以上就介紹了php 讀寫 xml,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!