複製代碼 代碼如下:<?php
//建立一個新的DOM文檔
$dom = new DomDocument();
//在根節點建立departs標籤
$departs = $dom->createElement('departs');
$dom->appendChild($departs);
//在departs標籤下建立depart子標籤
$depart = $dom->createElement('depart');
$departs->appendChild($depart);
//在depart標籤下建立employees子標籤
$employees = $dom->createElement('employees');
$depart->appendChild($employees);
//在employees標籤下建立employee子標籤
$employee = $dom->createElement('employee');
$employees->appendChild($employee);
//在employee標籤下建立serial_no子標籤
$serial_no = $dom->createElement('serial_no');
$employee->appendChild($serial_no);
//為serial_no標籤添加值節點100001
$serial_no_value = $dom->createTextNode('100001');
$serial_no->appendChild($serial_no_value);
//輸出XML資料
echo $dom->saveXML();
?>
複製代碼 代碼如下:<?php
$dom = new DomDocument(); //建立DOM對象
$dom->load('example.xml'); //讀取XML檔案
$root = $dom->documentElement; //擷取XML資料的根
read_child($root); //調用read_child函數讀取根對象
function read_child($node)
{
$children = $node->childNodes; //獲得$node的所有子節點
foreach($children as $e) //迴圈讀取每一個子節點
{
if($e->nodeType == XML_TEXT_NODE) //如果子節點為文本型則輸出
{
echo $e->nodeValue."<BR>";
}
else if($e->nodeType == XML_ELEMENT_NODE) //如果子節點為節點對象,則調用函數處理
{
read_child($e);
}
}
}
?>