Method One
| The code is as follows |
Copy Code |
|
function Xml_out ($content, $charset = ' utf-8 ') {
@header ("Expires:-1");
@header ("Cache-control:no-store, Private, post-check=0, Pre-check=0, max-age=0", FALSE);
@header ("Pragma:no-cache");
@header ("Content-type:application/xml; charset= $charset ");
Echo ' < '. "? xml version=" 1.0 "encoding=" $charset "? >n";
echo "<root><! [cdata[]. Trim ($content). "]]></root>";
Exit ();
} |
Method Two
| The code is as follows |
Copy Code |
|
<?php
Header ("Content-type:text/xml");
echo "<?xml version=" 1.0 "encoding=" UTF-8 "?>";
echo "<users><user><name> Little rookie </name><age>24</age><sex> man </sex> </user><user><name> Yan Yan </name><age>23</age><sex> female </sex></user ></users> ";
?> |
Method Three
using DOMDocument to generate XML files
Create nodes using the CreateElement method,
Create text content using the createTextNode method,
Add child nodes using the AppendChild method,
Creating properties using the CreateAttribute method
| The code is as follows |
Copy Code |
? Php
$data _array = Array (
Array
' title ' => ' Title1 ',
' Content ' => ' content1 ',
' pubdate ' => ' 2009-10-11 ',
),
Array
' title ' => ' Title2 ',
' Content ' => ' Content2 ',
' pubdate ' => ' 2009-11-11 ',
)
);
Property array
$attribute _array = Array (
' title ' => Array (
' Size ' => 1
)
);
Create an XML document and set up an XML version and encoding ...
$dom =new DOMDocument (' 1.0 ', ' utf-8 ');
To create a root node
$article = $dom->createelement (' article ');
$dom->appendchild ($article);
foreach ($data _array as $data) {
$item = $dom->createelement (' item ');
$article->appendchild ($item);
Create_item ($dom, $item, $data, $attribute _array);
}
echo $dom->savexml ();
function Create_item ($dom, $item, $data, $attribute) {
if (Is_array ($data)) {
foreach ($data as $key => $val) {
Creating elements
$ $key = $dom->createelement ($key);
$item->appendchild ($ $key);
Create an element value
$text = $dom->createtextnode ($val);
$ $key->appendchild ($text);
if (Isset ($attribute [$key])) {//If there is a related property to be set for this field
foreach ($attribute [$key] as $akey => $row) {
To create an attribute node
$ $akey = $dom->createattribute ($akey);
$ $key->appendchild ($ $akey);
Creating a property value node
$aval = $dom->createtextnode ($row);
$ $akey->appendchild ($aval);
}
}//End If
}
}//End If
}//End Function
?> |
Method Four
SimpleXML input XML format encoding
As part of the PHP core, simplexml can transform XML into objects, but sometimes I need to encode the XML format of the output;
Code:
| The code is as follows |
Copy Code |
|
$XML = new SimpleXMLElement ("<foo/>"); Echo ($XML->asxml ()); |
Output results:
| The code is as follows |
Copy Code |
|
<?xml version= "1.0"?> <foo/> |
If you want to output:
| code is as follows |
copy code |
|
<?xml Version= "1.0" encoding= "UTF-8"?> <foo/> |