自訂php類(尋找/修改)xml文檔_PHP教程

來源:互聯網
上載者:User
近期在看PHP的教學視頻,其中講到了 PHP 操作 xml 文檔,學了點兒 DOMDocument 類。自己查手冊又全英文,看不大懂。但還是自己寫了個類,實現了尋找 xml 節點,並修改節點值。背景解說完畢,且看代碼如下:
複製代碼 代碼如下:
/*

<班級>
<學生 number="101">
<名字>孫悟空
<名字>孫行者
<年齡>猴精猴精
<介紹>

<學生 number="102">
<名字>白骨精
<年齡>140
<介紹>幻化萬千

<學生 number="103">
<名字>豬八戒
<名字>豬無能
<年齡>200
<介紹>能吃會睡


*/
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);//節點
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('學生','年齡','103');//找到 年齡=103 的豬八戒
$test->update('小豬豬', '名字', false, 1); //把豬八戒的第二個名字改成:小豬豬
$test->save('new.xml'); //儲存成新檔案

http://www.bkjia.com/PHPjc/326709.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/326709.htmlTechArticle近期在看PHP的教學視頻,其中講到了 PHP 操作 xml 文檔,學了點兒 DOMDocument 類。自己查手冊又全英文,看不大懂。但還是自己寫了個類,實現...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.