<?php
header('content-type:text/html;charset=utf-8');
// DOM 技术解析xml文件,实际就是读取显示xml文件的内容
$xml = new DOMDocument();
$xml->load('book.xml');
$books = $xml->getElementsByTagName("book");
foreach($books as $b){
echo $b->getAttribute('id');
echo $b->getElementsByTagName('name')->item(0)->nodeValue;
echo $b->getElementsByTagName('price')->item(0)->nodeValue;
echo '<hr/>';
}
//建立xml文件基本方法
$xmlinfo= <<<aaa
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book id="100">
<name>PHP技术开发</name>
<price>80</price>
</book>
<book id="101">
<name>Oracle技术</name>
<price>120</price>
</book>
<book id="102">
<name>MySQL数据库技术</name>
<price>89</price>
</book>
<book id="103">
<name>Java项目实例</name>
<price>90</price>
</book>
<book id="104">
<name>Ajax技术开发</name>
<price>50</price>
</book>
</books>
aaa;
//file_put_contents('b.xml',$xmlinfo);
//利dom方式建立xml文件
/*
$x = new DOMDocument(1.0,"utf-8");
$x->formatOutput=true;
//建立根元素
$root = $x->createElement('books');
//建立元素
$b1 = $x->createElement('book');
$id1 = $x->createAttribute('id');
$id1v = $x->createTextNode('100');
$bn = $x->createElement('name','php开发');
$bp = $x->createElement('price',80);
$id1->appendChild($id1v);
$b1->appendChild($id1);
$b1->appendChild($bn);
$b1->appendChild($bp);
$root->appendChild($b1);
$x->appendChild($root);
$x->save('s.xml');
*/
//删除s.xml文件中的一个元素
$doc = new DOMDocument(1.0,'utf-8');
$doc->formatOutput = true;
$doc->load('s.xml');
//$root= $doc->getElementsByTagName("books")->item(0);
//$book = $doc->getElementsByTagName('book')->item(2);
//$root->removeChild($book);
//$book = $doc->getElementsByTagName('book')->item(0);
//$book->parentNode->removeChild($book);
//添加元素
$idv = $doc->createTextNode($doc->getElementsByTagName('book')->length+100);
$id = $doc->createAttribute('id');
$id->appendChild($idv);
$book = $doc->createElement('book');
$name = $doc->createElement('name','java项目');
$price = $doc->createElement('price',100);
$book->appendChild($id);
$book->appendChild($name);
$book->appendChild($price);
$root = $doc->getElementsByTagName("books")->item(0);
$root->appendChild($book);
$doc->save('s.xml');
?>