PHP generates simple code for XML (example description)

Source: Internet
Author: User
Tags cdata data structures

When working with xml-based applications, developers often need to build XML-encoded data structures. For example, the XML state template that is based on user input in the Web, the server requests XML statements, and customer responses based on the run-time parameters.
&NBSP
    Although the construction of XML data structures can be time-consuming, everything becomes straightforward if you use a sophisticated PHP DOM application interface. This article the The PHP Training instructor will introduce you to the main features of the PHP DOM application interface, demonstrating how to generate a correct XML complete file and save it to disk.
 
    Create document type declarations
    Generally, XML declarations are placed at the top of the document. Declaring in PHP is simple: Just instantiate an object of a DOM document class and give it a version number. Viewer List A:
    List A

  code is as follows copy code
 &nbs p;  <?php
   /create doctype
    $dom = new DOMDocument ("1.0");
&nbs p;  //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'll explain this in detail later, and now you just need to realize that it's used to output the current snapshot of an XML document to a file or browser. In this example, to enhance readability, I have exported the ASCII text directly to the browser. In practical applications, you can send the Text/xml header file to the browser.
If you view the output in a browser, you can see the following code:
<?xml version= "1.0"?>
Adding elements and Text nodes
The truly powerful function of XML comes from its elements and encapsulated content. Fortunately, as soon as you initialize the DOM document, many of the operations become simple. This procedure includes 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 through the 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, the element or text node is added to the parent node in the XML document tree.
The following example will clearly demonstrate these 2 steps, and check out program list B.

Program List B

The code is as follows Copy Code

 <?php
   /create doctype
    $dom = new DOMDocument ("1.0");
& nbsp;  //Display document in browser as plain text
   /For readability purposes
&nbs p;   header ("Content-type:text/plain");
   //Create root element
     $root = $dom->createelement ("toppings");
    $dom->appendchild ($root);
    //Create child element
    $item = $dom->createelement ("item");
  & nbsp $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 the name <toppings> and put it in the XML header file. Then I build the element named <item> and make it the root element. Finally, I created a text node with a value of "pepperoni" and attributed it to the <item> element. The final results are as follows:

<?xml version= "1.0"?>
<toppings>
<item>pepperoniwww.111cn.net</item>
</toppings>

If you want to add another topping, simply create another <item> and add a different content, as shown in Listing C of the program.
Program List C

The code is as follows Copy Code

<?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 listing C of the execution program:
<?xml version= "1.0"?>
<toppings>
<item>pepperoni</item>
<item>tomato</item>
</toppings>

Add properties

Before we continue to share PHP generated XML simple Instance code (1) content, the following Beijing PHP training and then continue to share PHP generated XML simple Instance code (2) of the content.

By using attributes, you can also add appropriate information to the element. For the PHP DOM API, it takes two steps to add a property: first create a node with the name of the property by using 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 List D for details.
Program List D

The code is as follows Copy Code
<?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 looks like this:
<?xml version= "1.0"?>
<toppings>
<item price= "4" >pepperoni</item>
</toppings>

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 well by invoking the createcdatasection () and Createprocessinginstruction () methods of DOM document objects , see the list of programs E.
Program List E

The code is as follows Copy Code
<?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 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 looks like this:
<?xml version= "1.0"?>
<toppings>
<item price= "4" >pepperoni</item>
<! [cdata[
Customer requests that pizza is sliced into square pieces
]]>
<?pizza Bake ()? >
</toppings>


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 (listing F):
Program List F

The code is as follows Copy Code
<?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 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 you can test.
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 ' 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)) {
$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;
}
}
?>

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.