一 、XML 读
1.1、 首先同目录定义好一个XML文件 :
book.xml
<?xml version="1.0" encoding="utf-8"?> <books> <book> <id>1</id> <name>书本001</name> </book> <book> <id>2</id> <name>书本002</name> </book> <book> <id>3</id> <name>书本003</name> </book> <title>这是标题</title> </books>
1.2 通过 getElementsByTagName 读取XML
$xml=new DOMDocument(); $xml->load("book.xml"); // 通过 getElementsByTagName 读取 foreach($xml->getElementsByTagName(‘book‘) as $book) { $id=$book->getElementsByTagName("id"); $name=$book->getElementsByTagName("name"); echo "id:".$id->item(0)->nodeValue.",name:".$name->item(0)->nodeValue."<br/>"; }
1.3 通过 simplexml_import_dom 直接读取属性
// 通过simplexml_import_dom 直接读取属性 $simplexml = simplexml_import_dom($xml); echo "sid->title:".$simplexml->title;
echo "the id is :".$simplexml->book[0]->id;echo "the id is :".$simplexml->title;
二 、XML 创建
2.1、通过 字符串 创建XML document 元素
$xmlString=<<<XML <?xml version="1.0" encoding="utf-8"?> <books> <book> <id>1</id> <name>书本001</name> </book> <book> <id>2</id> <name>书本002</name> </book> <book> <id>3</id> <name>书本003</name> </book> <title>这是标题</title> </books> XML; $dom=new DomDocument; $dom->loadXML($xmlString);
2.2 通过 DOMDocument api 创建XML 对象 ( 子节点,节点属性 ,CDATA属性值标记)
class buildXml { /* * 创建一个XML元素 * */ private function createXml() { $dom = new DOMDocument("1.0"); $books = $dom->createElement("books"); for ($i = 0; $i < 4; $i++) { $book = $dom->createElement("book"); // 为book 节点添加一个属性 $price = $dom->createAttribute("price"); $priceValue = $dom->createTextNode($i * 10); $price->appendChild($priceValue); $book->appendChild($price); // 添加一个id 接点元素 并赋值 $id = $dom->createElement("id"); $idValue = $dom->createTextNode($i); $id->appendChild($idValue); $book->appendChild($id); // 添加一个待 CDATA标识的内容 $title = $dom->createElement("title"); $titleValue = $dom->createCDATASection("这是一个带CDATA标签的内容"); $title->appendChild($titleValue); $book->appendChild($title); $books->appendChild($book); } $dom->appendChild($books); return $dom->saveXML(); } // 输出XML public function printXML() { header("Content-Type: text/xml"); echo $this->createXml(); } // 保存XML public function saveXML() { $result = false; try { //打开要写入 XML数据的文件 $fp = fopen("newxml.xml", "w"); //写入 XML数据 fwrite($fp, $this->createXml()); //关闭文件 fclose($fp); $result = true; } catch (Exception $e) { print $e->getMessage(); exit(); } return $result; } }
2.3 http 输出 XML
require_once "buildXml.php";
$xml = new buildXml; echo $xml->printXML();
2.4 已文件形式保存 XML
require_once "buildXml.php"; $xml = new buildXml; $xml->saveXML();
时间: 2024-10-16 10:42:38