php操作xml
php  /  管理员 发布于 7年前   223
要操作的数据 XML几个基本概念 加载xml 读取/遍历节点与属性 foreach($bookElements as $book){ 当然对于很多属性,只想读一个,可以通过item(index)方法按索引读取 修改属性/节点 } 对属性修改可以直接访问其nodeValue改动,也可以使用setAttribute方法,改动完了别忘了使用save保存。 添加元素/属性 $publisher=$books->createAttribute('publisher');#创建新属性,方法二 $author=$books->createElement('author');#创建子元素 $books->documentElement->appendChild($newBook);#添加整个节点 删除属性/节点 $second=$bookElements->item(1); $books->save($path); 122 在 123 在 原梓番博客 在 博主 在 1111 在
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
David Flanagan
Luke Welling
Laura Thomson
David Courley
Brian Totty
1、 节点:节点也就是很多程序语言中处理XML时的Node,节点是一个比较宽泛的概念,在XML中元素,属性,名字空间,注释,文本内容,处理指令,还有整个文档都属于节点,也就是说XML文档中每个独立的一小部分都是节点,
2、元素:很多程序语言都有对XML处理,节点是一个很宽泛的概念,因为要统一API,对节点不会有过多方法,而元素也就是Element是节点的一个子集,简单讲就是
3、属性:这个比较好理解,在<>里面的类似XX=”OO”等东西都是属性节点
4、转义字符:和HTML等类似,xml也有语言占用的符号,想使用的这些特殊字符的时候需要转义
DOMDocument对象
我使用的是DOMDocument对象来操作xml,感觉用起来比simpleXml科学一些,当然第一天使用php,纯属个人感觉。DOMDocument有几个常用的属性和方法。
$path=$_SERVER["DOCUMENT_ROOT"].'/books.xml';
$books=new DOMDocument();
$books->load($path);
$bookElements=$books->getElementsByTagName('book');
foreach ($book->attributes as $attr) {
echo strtoupper($attr->nodeName).' ―― '.$attr->nodeValue.'
';
}
echo "AUTHOR: ";
foreach ($book->getElementsByTagName('author') as $author) {
echo $author->nodeValue.' ';
}
echo '
';
}
echo $book->attributes->item(1)->nodeValue;
还可以通过强大的xpath查询
复制代码 代码如下:
还可以通过强大的xpath查询
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);
$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->nodeValue='Apress L.P';
$newBook->appendChild($publisher); #把属性添加到元素上
$author->nodeValue='Matt Zandstra';
$newBook->appendChild($author);#把子元素添加到父元素上
$books->save($path);
$first=$bookElements->item(0);
$first->removeAttribute('publisher');
$second->parentNode->removeChild($second);
初学php文章肯定有很多谬误,希望大家批评指正,共同进步。您可能感兴趣的文章:
上一条:
PHP生成Gif图片验证码
下一条:
关于php内存不够用的快速解决方法