This article mainly introduces the method of creating xml documents based on PHP based on DOM, and analyzes the relevant operating skills of using PHP to create xml format files using DOM in the form of examples. Friends in need can refer to the following
Examples of this article Introduces PHP's method of creating xml documents based on DOM. Share it with everyone for your reference, the details are as follows:
DOM creates xml document
Use dom to create the following document:
<booklist> <book id="1"> <title>天龙八部</title> <author>金庸</author> <content> <![CDATA[ 天龙八部是金庸写的一本武侠小说,非常好看! ]]> </content> </book> </booklist>
Implementation steps:
1. Create DOM object——》2. Create node——》3. Create subordinate node——》4. Add subordinate node to superior node——》5. Create attributes Node——》6. Add the attribute node to the node with the attribute——》7. If there are still nodes, repeat steps 2~6——》8. Add the highest-level node (i.e. root node) to the DOM object Medium——》9. Open or save xml document.
In the process of creating a node, you can start from the lowest node or the root node. The implementation code is as follows:
<?php header('Content-Type: text/xml;'); $dom = new DOMDocument('1.0','utf-8');//建立DOM对象 $no1 = $dom->createElement('booklist');//创建普通节点:booklist $dom->appendChild($no1);//把booklist节点加入到DOM文档中 $no2 = $dom->createElement('book');//创建book节点 $no1->appendChild($no2);//把book节点加入到booklist节点中 $no3 = $dom->createAttribute('id');//创建属性节点:id $no3->value = 1;//给属性节点赋值 $no2->appendChild($no3);//把属性节点加入到book节点中 $no3 = $dom->createElement('title'); $no2->appendChild($no3); $no4 = $dom->createTextNode('天龙八部');//创建文本节点:天龙八部 $no3->appendChild($no4);//把天龙八部节点加入到book节点中 $no3 = $dom->createElement('author'); $no2->appendChild($no3); $no4 = $dom->createTextNode('金庸');//创建文本节点:天龙八部 $no3->appendChild($no4);//把天龙八部节点加入到book节点中 $no3 = $dom->createElement('content'); $no2->appendChild($no3); $no4 = $dom->createCDATASection('天龙八部是金庸写的一本武侠小说,非常好看!');//创建文CDATA节点 $no3->appendChild($no4);//把天龙八部节点加入到book节点中 header('Content-type:text/html;charset=utf-8'); echo $dom->save('booklist.xml')?'存储成功':'存储失败';//存储为xml文档 /*直接以xml文档格式打开 header('Content-type:text/xml'); echo $dom->savexml(); */ ?>
For more examples of how PHP creates xml documents based on DOM, please pay attention to the PHP Chinese website for related articles!