自定義php類(查找/修改)xml文檔_PHP教程
推薦:PHP字符過濾函數(shù)去除字符串最后一個逗號(rtrim)PHP字符過濾函數(shù)去除字符串最后一個逗號,用php自帶的函數(shù)比較容易解決
近期在看PHP的教學(xué)視頻,其中講到了 PHP 操作 xml 文檔,學(xué)了點兒 DOMDocument 類。自己查手冊又全英文,看不大懂。但還是自己寫了個類,實現(xiàn)了查找 xml 節(jié)點,并修改節(jié)點值。背景解說完畢,且看代碼如下:復(fù)制代碼 代碼如下:www.hl5o.cn
/*
<?xml version="1.0" encoding="UTF-8"?>
<班級>
<學(xué)生 number="101">
<名字>孫悟空</名字>
<名字>孫行者</名字>
<年齡>猴精猴精</年齡>
<介紹></介紹>
</學(xué)生>
<學(xué)生 number="102">
<名字>白骨精</名字>
<年齡>140</年齡>
<介紹>幻化萬千</介紹>
</學(xué)生>
<學(xué)生 number="103">
<名字>豬八戒</名字>
<名字>豬無能</名字>
<年齡>200</年齡>
<介紹>能吃會睡</介紹>
</學(xué)生>
</班級>
*/
class xmlDom{
public $version;
public $encoding;
private $xml;
private $items;
private $seachNode = '';
private $seachItem = '';
private $seachValue = '';
public $writeBytes = 0;
function __construct($xmlFile ='', $version ='1.0', $encoding = 'UTF-8'){
$this->version = $version;
$this->encoding = $encoding;
$this->xml = new DOMDocument($version, $encoding);
if($xmlFile)$this->xml->load($xmlFile);
}
function getRootEle($rootTag){
$this->xmlRoot = $this->xml->getElementsByTagName($rootTag)->item(0);
}
function getSeachItem($itemsTag, $seachNode, $seachValue){
$this->items = $this->xml->getElementsByTagName($itemsTag);
$this->items->length;
for($i=0; $i<$this->items->length; $i++){
$item = $this->items->item($i);//元素
$node = $item->getElementsByTagName($seachNode);//節(jié)點
for($j = 0; $j< $node->length; $j++){
$subNode = $node->item($j);
if($seachValue == $subNode->nodeValue){
$this->seachNode = $subNode;
$this->seachItem = $item;
$this->seachValue = $subNode->nodeValue;
break(2);
}
}
}
return ($this->seachNode) ? true : false;
}
function update($nodeValue, $nodeTag = '',$append = false, $index = 0){
if($append){
if($nodeTag)
$this->seachItem->getElementsByTagName($nodeTag)->item($index)->nodeValue += $nodeValue;
else
$this->seachNode->nodeValue += $nodeValue;
}else{
if($nodeTag)
$this->seachItem->getElementsByTagName($nodeTag)->item($index)->nodeValue = $nodeValue;
else
$this->seachNode->nodeValue = $nodeValue;
}
}
function save($filename){
$this->writeBytes = $this->xml->save($filename);
return ($this->writeBytes) ? true : false;
}
}
$test = new xmlDom('student.xml');
$test->getSeachItem('學(xué)生','年齡','103');//找到 年齡=103 的豬八戒
$test->update('小豬豬', '名字', false, 1); //把豬八戒的第二個名字改成:小豬豬
$test->save('new.xml'); //保存成新文件
分享:php中將html中的br換行符轉(zhuǎn)換為文本輸入中的換行符PHP中的有個非常好的函數(shù):nl2br(),將文本框中的換行轉(zhuǎn)換為HTML頁面的br /,但是如何實現(xiàn)將html中的br /換行符轉(zhuǎn)換為文本框中的換行符呢
相關(guān)PHP教程:
- PHPNOW安裝Memcached擴(kuò)展方法詳解
- php記錄頁面代碼執(zhí)行時間
- PHP中獎概率的抽獎算法程序代碼
- apache設(shè)置靜態(tài)文件緩存方法介紹
- php對圖像的各種處理函數(shù)代碼小結(jié)
- PHP 關(guān)于訪問控制的和運算符優(yōu)先級介紹
- 關(guān)于PHP語言構(gòu)造器介紹
- php/js獲取客戶端mac地址的實現(xiàn)代碼
- php5.5新數(shù)組函數(shù)array_column使用
- PHP preg_match的匹配多國語言的技巧
- php 中序列化和json使用介紹
- php采集文章中的圖片獲取替換到本地
- 相關(guān)鏈接:
- 教程說明:
PHP教程-自定義php類(查找/修改)xml文檔
。