search
HomeBackend DevelopmentPHP TutorialExample parsing of xml generated based on php

Example parsing of xml generated based on php

php generates xml simple example code

Use PHP DOMDocument to create dynamic XML files

When dealing with XML-based applications , developers often need to create XML-encoded data structures. For example, XML status templates in the Web based on user input, server request XML statements, and client responses based on runtime parameters.
Although the construction of XML data structure is time-consuming, if you use the mature PHP DOM application programming interface, everything will become simple and clear. This article will introduce you to the main functions of the PHP DOM application interface and demonstrate how to generate a correct complete XML file and save it to disk.
Create document type declaration
Generally speaking, the XML declaration is placed at the top of the document. Declaration in PHP is very simple: just instantiate an object of the DOM document class and give it a version number. View program listing A:
Program listing A

<?php 
    // create doctype 
    $dom = new DOMDocument("1.0"); 
    // display document in browser as plain text 
    // for readability purposes 
    header("Content-Type: text/plain"); 
    // save and display tree 
    echo $dom->saveXML(); 
?>

Please note the saveXML() method of the DOM document object. I'll go into more detail about this method later, but for now you just need to briefly realize that it is used to output the current snapshot of the XML document to a file or browser. In this example, I've output the ASCII text directly to the browser to enhance readability. In practical applications, text/XML header files can be sent to the browser.


If you view the output in a browser, you can see the following code:

Add elements and text nodes
The real power of XML comes from its elements and encapsulated content. Fortunately, once you initialize the DOM document, many operations become very simple. This process includes the following two steps:
For each element or text node you want to add, call the createElement() or createTextNode() method of the DOM document object through the element name or text content. This creates a new object corresponding to the element or text node.
Add an element or text node to the parent node in the XML document tree by calling the node's appendChild() method and passing it the object created in the previous step.
The following example will clearly demonstrate these 2 steps, please see Listing B.
Program List B

<?php 
    // create doctype 
    $dom = new DOMDocument("1.0"); 
     
    // display document in browser as plain text 
    // for readability purposes 
    header("Content-Type: text/plain");
      
    // create root element 
    $root = $dom->createElement("toppings"); 
    $dom->appendChild($root); 
     
    // create child element 
    $item = $dom->createElement("item"); 
    $root->appendChild($item); 
     
    // create text node 
    $text = $dom->createTextNode("pepperoni"); 
    $item->appendChild($text); 
     
    // save and display tree 
    echo $dom->saveXML(); 
?>

Here, I first create a root element named and attribute it to the XML header file. Then, I create an element named and make it the root element. Finally, I create a text node with a value of "pepperoni" and assign it to the element. The end result is as follows:

<?xml version="1.0"?> 
<toppings> 
    <item>pepperoni</item> 
</toppings>

If you want to add another topping, just create another and add different content, as shown in Listing C.
Program Listing C

<?php 
    // create doctype 
    $dom = new DOMDocument("1.0"); 
     
    // display document in browser as plain text 
    // for readability purposes 
    header("Content-Type: text/plain"); 
     
    // create root element 
    $root = $dom->createElement("toppings"); 
     
    $dom->appendChild($root); 
    // create child element 
     
    $item = $dom->createElement("item"); 
    $root->appendChild($item); 
     
    // create text node 
    $text = $dom->createTextNode("pepperoni"); 
    $item->appendChild($text); 
     
    // create child element 
    $item = $dom->createElement("item"); 
    $root->appendChild($item); 
     
    // create another text node 
    $text = $dom->createTextNode("tomato"); 
    $item->appendChild($text); 
     
    // save and display tree 
    echo $dom->saveXML(); 
?>

The following is the output after executing Program Listing C:

<?xml version="1.0"?> 
<toppings> 
    <item>pepperoni</item> 
    <item>tomato</item> 
</toppings>

Add attributes
By using attributes, you can also add appropriate information to elements. For the PHP DOM API, adding an attribute requires two steps: first use the createAttribute() method of the DOM document object to create a node with the attribute name, and then add the document node to the attribute node with the attribute value. See Listing D for details.
Program List D

<?php 
    // create doctype 
    $dom = new DOMDocument("1.0"); 
     
    // display document in browser as plain text 
    // for readability purposes 
    header("Content-Type: text/plain"); 
     
    // create root element 
    $root = $dom->createElement("toppings"); 
    $dom->appendChild($root); 
     
    // create child element 
    $item = $dom->createElement("item"); 
    $root->appendChild($item); 
     
    // create text node 
    $text = $dom->createTextNode("pepperoni"); 
    $item->appendChild($text); 
     
    // create attribute node 
    $price = $dom->createAttribute("price"); 
    $item->appendChild($price); 
     
    // create attribute value node 
    $priceValue = $dom->createTextNode("4"); 
    $price->appendChild($priceValue); 
     
    // save and display tree 
    echo $dom->saveXML(); 
?>

The output is as follows:

<?xml version="1.0"?> 
<toppings> 
    <item price="4">pepperoni</item> 
</toppings>

Add CDATA module and process wizard
Although the CDATA module and process wizard are not often used, by calling the DOM document object The createCDATASection() and createProcessingInstruction() methods, the PHP API also supports CDATA and process wizards well, see Listing E.
Program Listing E

<?php 
    // create doctype 
    // create doctype 
    $dom = new DOMDocument("1.0"); 
     
    // display document in browser as plain text 
    // for readability purposes 
    header("Content-Type: text/plain"); 
     
    // create root element 
    $root = $dom->createElement("toppings"); 
    $dom->appendChild($root); 
     
    // create child element 
    $item = $dom->createElement("item"); 
    $root->appendChild($item); 
     
    // create text node 
    $text = $dom->createTextNode("pepperoni"); 
    $item->appendChild($text); 
     
    // create attribute node 
    $price = $dom->createAttribute("price"); 
    $item->appendChild($price); 
     
    // create attribute value node 
    $priceValue = $dom->createTextNode("4"); 
    $price->appendChild($priceValue); 
     
    // create CDATA section 
    $cdata = $dom->createCDATASection(" Customer requests that pizza be sliced into 16 square pieces "); 
    $root->appendChild($cdata); 
     
    // create PI 
    $pi = $dom->createProcessingInstruction("pizza", "bake()"); 
    $root->appendChild($pi); 
     
    // save and display tree 
    echo $dom->saveXML(); 
?>

The output looks like this:

<?xml version="1.0"?> 
<toppings> 
<item price="4">pepperoni</item> 
<![CDATA[ 
Customer requests that pizza be sliced into 16 square pieces 
]]> 
<?pizza bake()?> 
</toppings>

Saving the results
Once you have achieved your goal, you can save the results in a file or store it in PHP variable. The results can be saved in a file by calling the save() method with a file name, or in a PHP variable by calling the saveXML() method. Please refer to the following example (Program List F):
Program List F

<?php 
    // create doctype 
    $dom = new DOMDocument("1.0"); 
     
    // create root element 
    $root = $dom->createElement("toppings"); 
    $dom->appendChild($root); 
    $dom->formatOutput=true; 
     
    // create child element 
    $item = $dom->createElement("item"); 
    $root->appendChild($item); 
     
    // create text node 
    $text = $dom->createTextNode("pepperoni"); 
    $item->appendChild($text); 
     
    // create attribute node 
    $price = $dom->createAttribute("price"); 
    $item->appendChild($price); 
     
    // create attribute value node 
    $priceValue = $dom->createTextNode("4"); 
    $price->appendChild($priceValue); 
     
    // create CDATA section 
    $cdata = $dom->createCDATASection(" Customer requests that pizza be 
    sliced into 16 square pieces "); 
    $root->appendChild($cdata); 
     
    // create PI 
    $pi = $dom->createProcessingInstruction("pizza", "bake()"); 
    $root->appendChild($pi); 
     
    // save tree to file 
    $dom->save("order.xml"); 
     
    // save tree to string 
    $order = $dom->save("order.xml"); 
?>

The following is a practical example, you can test it.
xml.php (generate xml)

<? 
    $conn = mysql_connect(&#39;localhost&#39;, &#39;root&#39;, &#39;123456&#39;) or die(&#39;Could not connect: &#39; . mysql_error()); 
    mysql_select_db(&#39;vdigital&#39;, $conn) or die (&#39;Can\&#39;t use database : &#39; . mysql_error()); 
    $str = "SELECT id,username FROM `admin` GROUP BY `id` ORDER BY `id` ASC"; 
    $result = mysql_query($str) or die("Invalid query: " . mysql_error()); 
    if($result) { 
        $xmlDoc = new DOMDocument(); 
        if(!file_exists("01.xml")){ 
            $xmlstr = "<?xml version=&#39;1.0&#39; encoding=&#39;utf-8&#39; ?><message></message>"; 
            $xmlDoc->loadXML($xmlstr); 
            $xmlDoc->save("01.xml"); 
        } else { 
        $xmlDoc->load("01.xml");
    } 
     
    $Root = $xmlDoc->documentElement; 
    while ($arr = mysql_fetch_array($result)){ 
        $node1 = $xmlDoc->createElement("id"); 
        $text = $xmlDoc->createTextNode(iconv("GB2312","UTF-8",$arr["id"])); 
        $node1->appendChild($text); 
        $node2 = $xmlDoc->createElement("name"); 
        $text2 = $xmlDoc->createTextNode(iconv("GB2312","UTF-8",$arr["username"])); 
        $node2->appendChild($text2); 
        $Root->appendChild($node1); 
        $Root->appendChild($node2); 
        $xmlDoc->save("01.xml"); 
        } 
    } 
    mysql_close($conn); 
?>

Recommended tutorial: "PHP Video Tutorial"

The above is the detailed content of Example parsing of xml generated based on php. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:liqingbo. If there is any infringement, please contact admin@php.cn delete
如何用PHP和XML实现网站的分页和导航如何用PHP和XML实现网站的分页和导航Jul 28, 2023 pm 12:31 PM

如何用PHP和XML实现网站的分页和导航导言:在开发一个网站时,分页和导航功能是很常见的需求。本文将介绍如何使用PHP和XML来实现网站的分页和导航功能。我们会先讨论分页的实现,然后再介绍导航的实现。一、分页的实现准备工作在开始实现分页之前,需要准备一个XML文件,用来存储网站的内容。XML文件的结构如下:&lt;articles&gt;&lt;art

XML外部实体注入漏洞的示例分析XML外部实体注入漏洞的示例分析May 11, 2023 pm 04:55 PM

一、XML外部实体注入XML外部实体注入漏洞也就是我们常说的XXE漏洞。XML作为一种使用较为广泛的数据传输格式,很多应用程序都包含有处理xml数据的代码,默认情况下,许多过时的或配置不当的XML处理器都会对外部实体进行引用。如果攻击者可以上传XML文档或者在XML文档中添加恶意内容,通过易受攻击的代码、依赖项或集成,就能够攻击包含缺陷的XML处理器。XXE漏洞的出现和开发语言无关,只要是应用程序中对xml数据做了解析,而这些数据又受用户控制,那么应用程序都可能受到XXE攻击。本篇文章以java

php如何将xml转为json格式?3种方法分享php如何将xml转为json格式?3种方法分享Mar 22, 2023 am 10:38 AM

当我们处理数据时经常会遇到将XML格式转换为JSON格式的需求。PHP有许多内置函数可以帮助我们执行这个操作。在本文中,我们将讨论将XML格式转换为JSON格式的不同方法。

Python中xmltodict对xml的操作方式是什么Python中xmltodict对xml的操作方式是什么May 04, 2023 pm 06:04 PM

Pythonxmltodict对xml的操作xmltodict是另一个简易的库,它致力于将XML变得像JSON.下面是一个简单的示例XML文件:elementsmoreelementselementaswell这是第三方包,在处理前先用pip来安装pipinstallxmltodict可以像下面这样访问里面的元素,属性及值:importxmltodictwithopen("test.xml")asfd:#将XML文件装载到dict里面doc=xmltodict.parse(f

xml中node和element的区别是什么xml中node和element的区别是什么Apr 19, 2022 pm 06:06 PM

xml中node和element的区别是:Element是元素,是一个小范围的定义,是数据的组成部分之一,必须是包含完整信息的结点才是元素;而Node是节点,是相对于TREE数据结构而言的,一个结点不一定是一个元素,一个元素一定是一个结点。

使用nmap-converter将nmap扫描结果XML转化为XLS实战的示例分析使用nmap-converter将nmap扫描结果XML转化为XLS实战的示例分析May 17, 2023 pm 01:04 PM

使用nmap-converter将nmap扫描结果XML转化为XLS实战1、前言作为网络安全从业人员,有时候需要使用端口扫描利器nmap进行大批量端口扫描,但Nmap的输出结果为.nmap、.xml和.gnmap三种格式,还有夹杂很多不需要的信息,处理起来十分不方便,而将输出结果转换为Excel表格,方面处理后期输出。因此,有技术大牛分享了将nmap报告转换为XLS的Python脚本。2、nmap-converter1)项目地址:https://github.com/mrschyte/nmap-

Python中怎么对XML文件的编码进行转换Python中怎么对XML文件的编码进行转换May 21, 2023 pm 12:22 PM

1.在Python中XML文件的编码问题1.Python使用的xml.etree.ElementTree库只支持解析和生成标准的UTF-8格式的编码2.常见GBK或GB2312等中文编码的XML文件,用以在老旧系统中保证XML对中文字符的记录能力3.XML文件开头有标识头,标识头指定了程序处理XML时应该使用的编码4.要修改编码,不仅要修改文件整体的编码,还要将标识头中encoding部分的值修改2.处理PythonXML文件的思路1.读取&解码:使用二进制模式读取XML文件,将文件变为

深度使用Scrapy:如何爬取HTML、XML、JSON数据?深度使用Scrapy:如何爬取HTML、XML、JSON数据?Jun 22, 2023 pm 05:58 PM

Scrapy是一款强大的Python爬虫框架,可以帮助我们快速、灵活地获取互联网上的数据。在实际爬取过程中,我们会经常遇到HTML、XML、JSON等各种数据格式。在这篇文章中,我们将介绍如何使用Scrapy分别爬取这三种数据格式的方法。一、爬取HTML数据创建Scrapy项目首先,我们需要创建一个Scrapy项目。打开命令行,输入以下命令:scrapys

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),