PHP simpleXML学习笔记
时间:2008-06-23 来源:hyeve
案例
messsages.xml文档内容如下:
?xml version='1.0' standalone='yes'?>
Messages>
msg id='1' author='zhangsan'>
title>This message title/title>
content>Here is the content/content>
time>2008-12-31 22:12:32/time>
reply id='11'>first reply/reply>
reply id='22'>last reply/reply>
/msg>
/Messages>
1 创建对象(构造初始的simpleXMLElement对象)
1.1 从Dom对象中构造
$dom = new DOMDocument();
$dom->loadXML("");
$xml = simplexml_import_dom($dom)
1.2 从仅包含根标签的XML文档中创建
$xml = simplexml_load_file('messages.xml');
// 当对一个已存在xml文档进行操作而非创建初始档时,也可以用这种方式。
1.3 直接写根标签字符串构造
$xml = simplexml_load_string('');
1.4 使用simpleXMLElement类的构造器构造
$xml = new SimpleXMLElement('');
// 推荐使用这种方式构造。
2 对XML文档进行操作
2.1 访问字段值及其属性
2.1.1 输出留言1的标题和第一条回复
echo $xml->msg->title;
echo $xml->msg->reply[0];
2.1.2 输出留言ID和第二条回复的ID(属性值)
echo $xml->msg['id'];
echo $xml->msg->reply[1]['id'];
// 第一维表示节点,第二维表示节点属性。数组索引标记自0开始。
2.2 遍历检索XML文档
2.2.1 遍历同名节点
// 依次输出所有回复的ID(属性)和内容(值)
foreach($xml->msg->reply as $reply){
echo $reply['id'].'. '.$reply.'
';
}
2.2.2 遍历子节点
// 输出留言1的所有子节点内容(值)
foreach($xml->msg->children() as $field){
echo $field.'
';
}
注:$simpleXMLElement->children()方法得到所有子节点内容(值)。
2.2.3 遍历节点属性
// 遍历msg节点的所有属性
foreach($xml->msg->attributes() as $key=>$val){
echo $key.' = '.$val.'
';
}
2.2.4 检索节点内容
// XPath 方法可以直接检索定位,双斜杠(//)表示任意深度
// 检索所有的回复信息
foreach($xml->xpath('//reply') as $reply){
echo $reply.'
';
}
2.3 新增及设置XML文档中的节点属性
2.3.1 新增节点
// 给留言添加ip节点
$xml->msg->ip = '202.12.33.12';
2.3.2 新增属性
// 给回复信息增加author属性
$xml->msg->reply['author'] = 'lisi';
2.3.3 设置节点内容(值)
// 重新设置留言时间
$xml->msg->time = '2008-06-21 12:32:12';
2.3.4 设置节点属性值
// 重设第二条回复的id
$xml->msg->[1]['id']='222';
2.4 输出及保存对象
echo $xml->asXML();
$xml->asXML('MessageNew.xml');
内容参考:《PHPER》乔聪的使用simpleXML处理XML文件。
未完待续
相关阅读 更多 +