PHP simple code for generating XML _php tutorial

Source: Internet
Author: User
Tags cdata
When working with XML-based applications, developers often need to create XML-encoded data structures. For example, XML state templates based on user input in the Web, server request XML statements, and customer responses based on run-time parameters.

Although the construction of XML data structures is time-consuming, if you use the mature PHP DOM application interface, everything will become straightforward. This Dahne PHP Training instructor will introduce you to the main features of the PHP DOM application interface, demonstrating how to generate a correct XML full file and save it to disk.

Create a document type declaration
Generally, XML declarations are placed at the top of the document. Declaring in PHP is simple: simply instantiate an object of a DOM document class and give it a version number. View Program listing A:
Program List A

code as follows
!--? php
//Create doc Type
$dom = new DOMDocument ("1.0");
//Display document in browser as plain text
//display document in Browse R as Plain text
//For readability purposes
Header ("Content-type:text/plain");
//Save and display tree
E Cho $dom->savexml ();
?

Notice the SaveXML () method of the DOM document object. I'll go into this in more detail later, and now you just need to simply recognize that it is used to output the current snapshot of an XML document to a file or browser. In this case, for readability, I have printed the ASCII text directly to the browser. In real-world applications, the Text/xml header file can be sent to the browser.
If you look at the output in a browser, you can see the following code:

Adding elements and Text nodes
The really powerful feature of XML is the content from its elements and encapsulation. Fortunately, once you initialize a DOM document, a lot of the operations become straightforward. This process consists of the following two steps:
For each element or text node that you want to add, call the createelement () or createTextNode () method of the DOM document object by element name or text content. This creates a new object that corresponds to the element or text node.
By calling the node's AppendChild () method and passing it to the object created in the previous step, and adding the element or text node to the parent node in the XML document tree.
The following example illustrates these 2 steps clearly, see program listing B.

Program Listing B

code as follows

!--? php
//creat E doctype
$dom = new DOMDocument ("1.0");
//Display document in browser as plain text
//for readability Purpo SES
Header ("Content-type:text/plain");
//create root element
$root = $dom->createelement ("toppings"); br> $dom->appendchild ($root);
//Create child element
$item = $dom->createelement ("item");
$root AppendChild ($item);
//Create text node
$text = $dom->createtextnode ("pepperoniwww.111cn.net");
$item- >appendchild ($text);
//Save and Display Tree
Echo $dom->savexml ();
?

Here, I first create a root element with a name and put it in the XML header file. Then, I build the element named and make it the root element. Finally, I created a text node with a value of "pepperoni" and attributed it to the element. The final result is as follows:



Pepperoniwww.111cn.net

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

The code is as follows

!--? php
//create DOCTYPE
$dom = new DOMDocument ("1.0");
//Display document in browser as plain Tex T
//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 manifest C:
!--? XML version= "1.0"?--"

pepperoni
tomato

Add Property

Before we continue to share with you the PHP generation XML Simple Instance code (1), the following Beijing PHP training then continue to share the PHP generation XML Simple Instance code (2) content.

By using properties, you can also add appropriate information to the element. For the PHP DOM API, adding attributes takes two steps: first create the node with the name of this property with the CreateAttribute () method of the DOM document object, and then add the document node to the attribute node that owns the property value. See program Listing D.
Program Listing D

The code is as follows
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:


Pepperoni

adding CDATA modules and Process Wizards
Although CDATA modules and process wizards are not often used, the PHP API also supports CDATA and process wizards by invoking the Createcdatasection () and Createprocessinginstruction () methods of DOM document objects. , see program List E.
Program List E

The code is as follows
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 is sliced into 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:


Pepperoni
<br />Customer requests that pizza is sliced into square pieces<br>


Save Results
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 the file name, and you can store the variables in PHP by calling the SaveXML () method. Please refer to the following example (program listing F):
Program List F

The code is as follows
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 is
Sliced into 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");
?>
Here are the actual examples that everyone can test under.
xml.php (Generate XML)
$conn = mysql_connect (' localhost ', ' root ', ' 123456 ') 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 the ' admin ' GROUP by ' id ' of ' 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 = " ";
$xmlDoc->loadxml ($XMLSTR);
$xmlDoc->save ("01.xml");
}
else {$xmlDoc->load ("01.xml");}
$Root = $xmlDoc->documentelement;
while ($arr = Mysql_fetch_array ($result)) {
$node 1 = $xmlDoc->createelement ("id");
$text = $xmlDoc->createtextnode (iconv ("GB2312", "UTF-8", $arr ["id"]);
$node 1->appendchild ($text);
$node 2 = $xmlDoc->createelement ("name");
$text 2 = $xmlDoc->createtextnode (iconv ("GB2312", "UTF-8", $arr ["username"]);
$node 2->appendchild ($text 2);
$Root->appendchild ($node 1);
$Root->appendchild ($node 2);
$xmlDoc->save ("01.xml");
}
}
Mysql_close ($conn);
?>
test.php (Application test)
$xmlDoc = new DOMDocument ();
$xmlDoc->load ("http://localhost/xml/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;
}
}
?>

http://www.bkjia.com/PHPjc/730237.html www.bkjia.com true http://www.bkjia.com/PHPjc/730237.html techarticle when working with XML-based applications, developers often need to create XML-encoded data structures. For example, the XML state template based on user input in the Web, the server requests XML statements, and is based on the OP ...

  • 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.