background image

$em

=

$em

->item(0);

$items

=

$em

->getElementsByTagName('item');

foreach

(

$items

 

as

 

$a

){

foreach

(

$a

->attributes 

as

 

$b

){

if

(

$b

->nodeValue=='Birthday'){

$a

->setAttribute('name','nBirthday');

}
}
}

$t

=

$dom

->createElement('item');

$t

->setAttribute('name','x');

$t

->setAttribute('src','www.baidu.com');

$t

->setAttribute('duration','duration');

$em

->appendChild(

$t

);

$dom

->save('x.xml');

?>
PHP 解析 XML 文档属性并编辑
代码如下

:

 
<?php 

//读取 xml 

 

$dom

=

new

 DOMDocument('1.0'); 

$dom

->load('data.xml'); 

$em

=

$dom

->getElementsByTagName('videos');

//最外层节点 

$em

=

$em

->item(0); 

$items

=

$em

->getElementsByTagName('video');

//节点 

//如果不用读取直接添加的话把下面这一段去掉即可 
foreach

(

$items

 

as

 

$a

){ 

foreach

(

$a

->attributes 

as

 

$b

){

//$b->nodeValue;节点属性的值$b->nodeName;节点属性的名称 

 echo

 

$b

->nodeName; 

 echo

 ":"; 

 echo

 

$b

->nodeValue; 

 echo

 "<br/>"; 


//下面是往 xml 写入一行新的 

$t

=

$dom

->createElement('video');

//<video 

$t

->setAttribute('title','1');

//<video name="data" 

$t

->setAttribute('src','2');

//<video name="data" src="2" 

$t

->setAttribute('img','1');

//<video name="data" img="1" 

$em

->appendChild(

$t

);

//<video name="data" img="1"/> 

$dom

->save('data.xml'); 

?>