PHP generates XML simple instance code

  • 2020-03-31 20:05:14
  • OfStack

When working with xml-based applications, developers often need to establish xml-encoded data structures. For example, XML state templates on the Web based on user input, server request XML statements, and customer responses based on run-time parameters.
While building XML data structures can be time consuming, using a mature PHP DOM application programming interface makes everything simple and straightforward. This article introduces you to the main features of the PHP DOM application interface, showing you how to generate a proper XML file and save it to disk.
Create a document type declaration
In general, XML declarations are placed at the top of the document. Declaration in PHP is simple: you simply instantiate the object of a 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 
// display document in browser as plain text 
// for readability purposes 
header("Content-Type: text/plain"); 
// save and display tree 
echo $dom->saveXML(); 
?> 

Notice the saveXML() method for the DOM document object. I'll talk more about this method later, but for now you simply need to recognize that it is used to output the current snapshot of an XML document to a file or browser. In this example, I have output ASCII text directly to the browser to enhance readability. In practice, you can send a text/XML header file to a browser.
If you view the output in a browser, you can see the following code:
< ? The XML version = "1.0"? >
Add elements and text nodes
The real power of XML comes from its elements and encapsulated content. Fortunately, once you initialize a DOM document, a lot of things become easy. This process consists of the following two steps:
For each element or text node you want to add, the createElement() or createTextNode() method of the DOM document object is called through the element name or text content. This creates a new object corresponding to an element or text node.
By calling the appendChild() method of the node, 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 clearly illustrates these two steps, as shown in listing B.
Program listing 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(); 
?> 

In this case, I'll first create a name < Toppings> And cause it to be included in the XML header file. And then I set up the name < Item> And attribute it to the root element. Finally, I create a text node with the value "pepperoni" and attribute it to < Item> Elements. 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. Item> And add different content, as shown in listing C of the program.
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(); 
?> 

Here 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 an element. For the PHP DOM API, adding an attribute requires two steps: first create the node with the attribute name using the createAttribute() method of the DOM document object, and then add the document node to the attribute node with the attribute value. See listing D for the procedure.
Program listing 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 the CDATA module and process wizard
Although not often use CDATA wizard module and process, but the DOM document object by calling the createCDATASection () and createProcessingInstruction () method, the PHP API can also support the CDATA and well process wizard, please see the program 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 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 the result
Once you've achieved your goal, you can save the results in a file or a variable stored in PHP. The results can be saved in a file by calling the save() method with the file name, and the saveXML() method can be stored in a variable in PHP. See the following example (program listing 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"); 
?> 

Here's a practical example, so you can test it out.
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)){ 
$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 testing)
 
<? 
$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; 
} 
} 
?> 

Related articles: