|
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內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
上一篇:php的Snoopy類案例講解
下一篇:實例分析php常量和變量的不同