復制代碼 代碼如下:
<?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);
}
}
}
?>