Php generates simple xml instance code

Source: Internet
Author: User

When processing XML-based applications, developers often need to establish XML-encoded data structures. For example, in the Web, XML status templates based on user input, XML statements for server requests, and customer responses based on runtime parameters.
Although the construction of XML data structures is time-consuming, everything becomes simple and clear if you use mature php dom application interfaces. 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 the disk.
Create document type declaration
Generally, the XML declaration is placed at the top of the document. The declaration in PHP is very simple: you only need to instantiate an object in the DOM document class and assign it a version number. View program list:
Program List Copy codeThe Code is as follows: <? Php
// Create doctype
$ Dom = new DOMDocument ("1.0 ");
// Display document in browser as plain text
// Display document in browser as plain text
// For readability purposes
Header ("Content-Type: text/plain ");
// Save and display tree
Echo $ dom-> saveXML ();
?>

Note the saveXML () method of the DOM Document Object. I will introduce this method in detail later. Now you just need to simply realize that it is used to output the current snapshot of the XML document to a file or browser. In this example, to enhance readability, I have output the ASCII code text directly to the browser. In practical applications, you can send text/XML header files to the browser.
For example, view the output in the browser, you can see the following code:
<? Xml version = "1.0"?>
Add element and text nodes
The real powerful feature of XML is its element and encapsulated content. Fortunately, once you initialize the DOM document, many operations become simple. This process includes the following two steps:
The createElement () or createTextNode () method of the DOM Document Object is called for each element or text node you want to add. This creates a new object corresponding to an element or a text node.
Call the appendChild () method of the node, pass it to the object created in the previous step, and add the element or text node to the parent node in the XML document tree.
The following example clearly demonstrates the two steps. Check program list B.
Program list BCopy codeThe Code is as follows: <? 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 ();
?>

In this example, I first create a root element named <toppings> and add it to the XML header file. Then, I create an element named <item> and assign it to the root element. Finally, I create a text node with the value "pepperoni" and assign it to the <item> element. The final result is as follows:Copy codeThe Code is as follows: <? Xml version = "1.0"?>
<Toppings>
<Item> pepperoni </item>
</Toppings>

If you want to add another topping, you only need to create another <item> and add different content, as shown in program listing C.
Program List CCopy codeThe Code is as follows: <? 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 output after executing program list C is as follows:Copy codeThe Code is as follows: <? Xml version = "1.0"?>
<Toppings>
<Item> pepperoni </item>
<Item> tomato </item>
</Toppings>

Add attribute
By using attributes, you can also add suitable information to an element. For php dom APIs, two steps are required to add attributes: first, use the createAttribute () method of the DOM Document Object to create a node with the attribute name, add the document node to the attribute node with the property value. For details, see program list D.
Program List DCopy codeThe Code is as follows: <? 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:Copy codeThe Code 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 createCDATASection () and createProcessingInstruction () Methods of DOM document objects, the php api can also well support CDATA and process wizard, see program list E.
Program List ECopy codeThe Code is as follows: <? 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 is as follows:Copy codeThe Code is as follows: <? Xml version = "1.0"?>
<Toppings>
<Item price = "4"> pepperoni </item>
<! [CDATA [
Customer requests that pizza be sliced into 16 square pieces
]>
<? Pizza bake ()?>
</Toppings>

Save result
Once you have achieved your goal, you can save the results in a file or a variable stored in PHP. You can save the results in a file by calling the save () method with a file name, And you can store the results in PHP variables by calling the saveXML () method. See the following example (program list F ):
Program list FCopy codeThe Code is as follows: <? 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)Copy codeThe Code is as follows: <?
$ Conn = mysql_connect ('localhost', 'root', '000000') or die ('could not connect: '. mysql_error ());
Mysql_select_db ('vdigital ', $ conn) or die ('can \' t use database: '. 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 = '1. 0' encoding = 'utf-8'?> <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 );
?>

Test. php (application test)Copy codeThe Code is as follows: <?
$ XmlDoc = new DOMDocument ();
$ XmlDoc-> load ("http: // localhost/xml. php ");
$ X = $ xmlDoc-> getElementsByTagName ('name ');
For ($ I = 0; $ I <= $ x-> length-1; $ I ++)
{
If (strpos ($ x-> item ($ I)-> nodeValue, "fang ")! = False)
{
Echo $ x-> item ($ I)-> parentNode-> childNodes-> item (1)-> nodeValue;
}
}
?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.