Home >Backend Development >PHP Problem >How to create xml file in php
Use DOM to create xml documents in PHP
Use dom to create the following documents:
<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 attribute 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——》9. Open or store the 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:
$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(); */
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to create xml file in php. For more information, please follow other related articles on the PHP Chinese website!