Home  >  Article  >  php教程  >  解析php DOMElement 操作xml 文档的实现代码

解析php DOMElement 操作xml 文档的实现代码

WBOY
WBOYOriginal
2016-06-13 11:53:091111browse

复制代码 代码如下:


/*
 





孙悟空名字>
孙行者名字>
123年龄>
介绍>
学生>


白骨精名字>
140年龄>
介绍内容介绍>
学生>
班级>
*/
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');

$itemsNodeList = $xmldoc->getElementsbyTagName('学生');
$itemElement = $itemsNodeList->item(0);//得到第一个完整的学生信息节点
$itemChildsNodeList = $itemElement->getElementsbyTagName('名字');//得到子节点“名字”,也许有多个名字
$itemChildNode = $itemChildsNodeList->item(0);//得到第一个名字节点
echo $itemChildNode->nodeValue;//输出节点值

//封装成函数
$nodeArr = array('名字', '年龄', '介绍');
function getNodeVal($xmldoc, $itemsName, $nodeArr){
    $items = $xmldoc->getElementsByTagName($itemsName);
     for($i=0; $i length; $i++){
        $item = $items->item($i);
        foreach($nodeArr as $node){
            $data[$i][] = $item->getElementsByTagName($node)->item(0)->nodeValue;
        }
    }
    return $data;
}

$data = getNodeVal($xmldoc, '学生', $nodeArr);
print_r($data);


复制代码 代码如下:


//添加节点
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');
$items = $xmldoc->getElementsByTagName('班级')->item(0);//根节点
$student =  $xmldoc->createElement('学生');//创建一个新的学生节点
$stu_name = $xmldoc->createElement('名字','张三');
$stu_age = $xmldoc->createElement('年龄','15');
$stu_intro = $xmldoc->createElement('介绍','动手能力强且成绩稳定');
$items->appendChild($student);
$student->appendChild($stu_name);
$student->appendChild($stu_age);
$student->appendChild($stu_intro);
$bytes = $xmldoc->save('datas.xml');
echo ($bytes)? "写入了: $bytes 字节" : '保存失败';

//删除节点
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');
$student = $xmldoc->getElementsByTagName('学生')->item(2);//直接找到要删除的节点
$student->parentNode->removeChild($student);//父节点的删除方法
$xmldoc->save('datas.xml');

//修改节点值
$student = $xmldoc->getElementsByTagName('学生')->item(2);
$student->getElementsByTagName('年龄')->item(0)->nodeValue += 10;
$student->setAttribute('id', '110');
$xmldoc->save('datas.xml');

//应用 Xpath 查找节点

$xml = new DOMDocument('1.0', 'UTF-8');
$xml->load('dat.xml');
$xpath = new DOMXPath($xml);
$nodeList = $xpath->query('/aaa/bbb/ddd/fff');
echo $nodeList->item(0)->nodeValue;

//SimpleXML 类操作 xml
/*



1001
200元
大明
天龙八部


1002
321元
张三
笑傲江湖


1004
182元
李四
读者


*/
$xml = simplexml_load_file('books.xml');
$books = $xml->book;
echo $books[1]->title . $books[1]['house'];//直接指向第二本书
foreach($xml as $item){
    echo $item->title,' ',$item['house'],'
';
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn