php100学习记录89-91

89讲,使用PHP DOM组件获取xml内容

<?php
$doc = new DOMDocument(); //实例化DOMDocument
$doc->load('book.xml');//载入book.xml
//$title= $doc->getElementsByTagName("book"); //获取内容
//echo $title->item(0)->nodeValue;  //打印内容
 
$book=$doc->getElementsByTagName("book");
foreach($book as $note){ //$book此时为二维数组
	echo $note->nodeValue."";
}
?>

book.xml

<?xml version="1.0" encoding="utf-8"?>
<php100>
<book>
 
   <author> 作者 </author>
</book>
<book>
 
   <author> 作者123 </author>
</book>
</php100>

90讲 使用PHP DOM组件创建xml内容

<?php
$doc = new DOMDocument('1.0', 'utf-8');  // 声明版本和编码
$doc -> formatOutput = true;  //格式XML输出
 
$root	= $doc -> createElement('root');	//创建一个标签
$index	= $doc -> createElement('index');	//创建一个标签
$conarea	= $doc -> createElement('conarea');	//创建一个标签
$id	    = $doc -> createAttribute('id');    //创建一个属性
 
$newsid = $doc -> createTextNode("1");		            //设置属性内容
$newstitle = $doc -> createTextNode("this is title");   //设置标签内容
$newsco = $doc -> createTextNode("this is content");   //设置标签内容
 
$id		-> appendChild($newsid);	//继承属性
$index	-> appendChild($id);	    //继承属性内容
$index	-> appendChild($newstitle);	//继承标签内容
$conarea-> appendChild($newsco);	//继承标签内容
 
$root	-> appendChild($index);		//继承子类
$root	-> appendChild($conarea);		//继承子类
$doc	-> appendChild($root);
$doc	-> save("php100.xml");      // 生成保存为XML
 
?>

91讲 使用PHP DOM组件修改、删除xml里的内容
index.php

<?php
/*===========修改xml中的值
$doc=new DOMDocument();
$doc->load("php100.xml");
$book= $doc->getElementsByTagName("php100");
 
foreach($book as $val){
	if($val->getAttribute("id")==3){
	echo $val->getAttribute("id");
	echo $val->getElementsByTagName("index")->item(0)->nodeValue="3333";
	echo "";
	}
	}
 
$doc->save("php100.xml");	*/
 
//===========删除xml中的值
$doc=new DOMDocument();
$doc->load("php100.xml");
 
$root=$doc->documentElement;
$book= $doc->getElementsByTagName("php100");
 
foreach($book as $val){
	if($val->getAttribute("id")==3){
	echo $val->getAttribute("id");
	echo $val->getElementsByTagName("index")->item(0)->nodeValue="3333";
	echo "";
	}
	if($val->getAttribute("id")==1){
		$root->removeChild($val);
	}
 
	}
 
$doc->save("php100.xml");
?>

php100.xml

<?xml version="1.0" encoding="utf-8"?>
<root>
<php100 id="1"><index>this is title1</index></php100>
<php100 id="2"><index>this is title2</index></php100>
<php100 id="3"><index>this is title3</index></php100>
<php100 id="4"><index>this is title4</index></php100>
</root>

Related posts:

Leave a Reply

Your email address will not be published.