|
lt; |
|
|
> |
gt; |
|
‘ |
apos; |
|
“ |
quot; |
我使用的是DOMDocument对象来操作xml,感觉用起来比simpleXml科学一些,当然第一天使用php,纯属个人感觉。DOMDocument有几个常用的属性和方法。
| 属性 | 作用 |
| attributes | 节点属性集合 |
| parentNode | 节点父节点 |
| documentElement | 文档根节点 |
| nodeName | 节点的名字 |
| nodeType | 节点类型 |
| nodeValue | 节点值 |
| Text | 节点及其子节点转换为文字 |
| 方法 | 作用 |
| appendChild | 为节点添加子节点 |
| createAttribute | 创建属性节点 |
| createElement | 创建元素 |
| getElementsByTagName | 通过节点名获取节点集合 |
| hasChildNodes | 判断节点是否有子节点 |
| insertBefore | 在节点 |
| Load | 通过文档路径加载xml |
| loadXML | 加载zml字符串 |
| removeChild | 删除子节点 |
| removeAttribute | 删除属性节点 |
| save | 保存文档 |
$path=$_SERVER["DOCUMENT_ROOT"].'/books.xml';
$books=new DOMDocument();
$books->load($path);
$bookElements=$books->getElementsByTagName('book');
foreach($bookElements as $book){
foreach ($book->attributes as $attr) {
echo strtoupper($attr->nodeName).' —— '.$attr->nodeValue.'br/>';
}
echo "AUTHOR: ";
foreach ($book->getElementsByTagName('author') as $author) {
echo $author->nodeValue.' ';
}
echo 'br/>br/>';
}

当然对于很多属性,只想读一个,可以通过item(index)方法按索引读取
echo $book->attributes->item(1)->nodeValue;
还可以通过强大的xpath查询
$xpath = new domxpath($books);
$bookElements=$xpath->query("/books/book");
foreach($bookElements as $book){
foreach ($book->attributes as $attr) {
#$book->setAttribute($attr->nodeName,strtoupper($attr->nodeValue));
$attr->nodeValue=strtoupper($attr->nodeValue);
}
echo "AUTHOR: ";
foreach ($book->getElementsByTagName('author') as $author) {
$author->nodeValue=strtoupper($author->nodeValue);
}
}
$books->save($path);

对属性修改可以直接访问其nodeValue改动,也可以使用setAttribute方法,改动完了别忘了使用save保存。
$book->setAttribute($attr->nodeName,strtoupper($attr->nodeValue)); $attr->nodeValue=strtoupper($attr->nodeValue);
$newBook=$books->createElement('book'); #创建新元素
$newBook->setAttribute('name','PHP Objects, Patterns, and Practice');#创建新属性,方法一
$publisher=$books->createAttribute('publisher');#创建新属性,方法二
$publisher->nodeValue='Apress L.P';
$newBook->appendChild($publisher); #把属性添加到元素上
$author=$books->createElement('author');#创建子元素
$author->nodeValue='Matt Zandstra';
$newBook->appendChild($author);#把子元素添加到父元素上
$books->documentElement->appendChild($newBook);#添加整个节点
$books->save($path);
$first=$bookElements->item(0);
$first->removeAttribute('publisher');
$second=$bookElements->item(1);
$second->parentNode->removeChild($second);
$books->save($path);

到此这篇关于使用php操作xml教程的文章就介绍到这了,更多相关php操作xml内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
咨 询 客 服