溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么自定義php類查找或修改xml文檔

發(fā)布時(shí)間:2021-07-22 18:25:02 來源:億速云 閱讀:116 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要講解了“怎么自定義php類查找或修改xml文檔”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么自定義php類查找或修改xml文檔”吧!

近期在看PHP的教學(xué)視頻,其中講到了 PHP 操作 xml 文檔,學(xué)了點(diǎn)兒 DOMDocument 類。自己查手冊又全英文,看不大懂。但還是自己寫了個(gè)類,實(shí)現(xiàn)了查找 xml 節(jié)點(diǎn),并修改節(jié)點(diǎn)值。背景解說完畢,且看代碼如下:

復(fù)制代碼 代碼如下:


/*
<?xml version="1.0" encoding="UTF-8"?>
<班級>
<學(xué)生 number="101">
<名字>孫悟空</名字>
<名字>孫行者</名字>
<年齡>猴精猴精</年齡>
<介紹></介紹>
</學(xué)生>
<學(xué)生 number="102">
<名字>白骨精</名字>
<年齡>140</年齡>
<介紹>幻化萬千</介紹>
</學(xué)生>
<學(xué)生 number="103">
<名字>豬八戒</名字>
<名字>豬無能</名字>
<年齡>200</年齡>
<介紹>能吃會(huì)睡</介紹>
</學(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é)點(diǎn)
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); //把豬八戒的第二個(gè)名字改成:小豬豬
$test->save('new.xml'); //保存成新文件

感謝各位的閱讀,以上就是“怎么自定義php類查找或修改xml文檔”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對怎么自定義php類查找或修改xml文檔這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

php
AI