How to create xml file in php

王林
Release: 2023-02-24 17:30:02
Original
2774 people have browsed it

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>
Copy after login

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(&#39;1.0&#39;,&#39;utf-8&#39;);//建立DOM对象
$no1 = $dom->createElement(&#39;booklist&#39;);//创建普通节点:booklist
$dom->appendChild($no1);//把booklist节点加入到DOM文档中
$no2 = $dom->createElement(&#39;book&#39;);//创建book节点
$no1->appendChild($no2);//把book节点加入到booklist节点中

$no3 = $dom->createAttribute(&#39;id&#39;);//创建属性节点:id
$no3->value = 1;//给属性节点赋值
$no2->appendChild($no3);//把属性节点加入到book节点中

$no3 = $dom->createElement(&#39;title&#39;);
$no2->appendChild($no3);
$no4 = $dom->createTextNode(&#39;天龙八部&#39;);//创建文本节点:天龙八部
$no3->appendChild($no4);//把天龙八部节点加入到book节点中

$no3 = $dom->createElement(&#39;author&#39;);
$no2->appendChild($no3);
$no4 = $dom->createTextNode(&#39;金庸&#39;);//创建文本节点:天龙八部
$no3->appendChild($no4);//把天龙八部节点加入到book节点中

$no3 = $dom->createElement(&#39;content&#39;);
$no2->appendChild($no3);
$no4 = $dom->createCDATASection(&#39;天龙八部是金庸写的一本武侠小说,非常好看!&#39;);//创建文CDATA节点
$no3->appendChild($no4);//把天龙八部节点加入到book节点中

header(&#39;Content-type:text/html;charset=utf-8&#39;);
echo $dom->save(&#39;booklist.xml&#39;)?&#39;存储成功&#39;:&#39;存储失败&#39;;//存储为xml文档

/*直接以xml文档格式打开
header(&#39;Content-type:text/xml&#39;);
echo $dom->savexml();
*/
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!