在PHP中處理xml文件

<?php
$xml = simplexml_load_file('Messages.xml');
//$xml = simplexml_load_string('Messages.xml');


//可以使用属性的方式访问子节点,通过节点的标签名可直接得到节点的内容


//节点的属性与值被封装成为关联数组的键与值

echo 'msg_size == '.sizeof($xml->msg).'<br>';
echo 'id == '.$xml->msg[1]['id'].'<br>';

echo "title == ".$xml->msg[1]->title.'<br />';

foreach ($xml->msg->reply as $reply){
	echo $reply['id'];
}

//children 方法得到所有子节点
foreach ($xml->msg->children() as $field){
echo $field.'<br>';
}

//設值
$xml->msg[1]->content = 'AAAAAAAAA';

//保存,如果參數為為空,即保存當前的XML
$xml->asXML('MessagesNew.xml');

?>



<?xml version='1.0' standalone='yes'?>
<Messages>
<msg id='1'>
<title>This is Title</title>
<content>Here is Content</content>
<time>2008-03-20 21:50:23</time>
<reply id='11'>reply 1</reply>
<reply id='12'>reply 2</reply>
</msg>

<msg id='2'>
<title>This is Title2</title>
<content>Here is Content</content>
<time>2008-03-20 21:50:23</time>
<reply id='11'>reply 1</reply>
<reply id='12'>reply 2</reply>
</msg>

</Messages>

你可能感兴趣的:(xml,PHP)