Describes how to generate xml source code in PHP. Php generates xml like a tree. you can add nodes one by one. you can add multiple subnodes under a parent node, functionmadexml () {get template information $ strTempInfo $ this-modelCmsObj-get php generates xml like a tree. add nodes one by one. you can add multiple subnodes under a parent node,
Function madexml ()
{
// Obtain template information
$ StrTempInfo = $ this-> modelCmsObj-> getTemplate (2007 );
$ ArrTemp = explode ("#", $ strTempInfo );
Array_shift ($ arrTemp );
$ ArrContents = array ();
Foreach ($ arrTemp as $ k => $ v)
{
$ ArrContents [$ k] = explode (",", $ v );
}
// Parse it into an xml file
$ ObjDom = new DOMDocument ("1.0 ");
Header ("Content-Type: text/plain ");
// Add element and text node
$ Root = $ objDom-> createElement ("recommend ");
$ ObjDom-> appendChild ($ root );
Foreach ($ arrContents as $ k => $ v)
{
$ Item = $ objDom-> createElement ("entry ");
$ Root-> appendChild ($ item );
$ Nextitem1 = $ objDom-> createElement ("simgurl ");
$ Nextitem2 = $ objDom-> createElement ("imgurl ");
$ Nextitem3 = $ objDom-> createElement ("fileurl ");
$ Item-> appendChild ($ nextitem1 );
$ Item-> appendChild ($ nextitem2 );
$ Item-> appendChild ($ nextitem3 );
$ Text1 = $ objDom-> createTextNode ($ v [0]);
$ Text = $ objDom-> createTextNode ($ v [1]);
$ Text2 = $ objDom-> createTextNode ($ v [2]);
$ Nextitem2-> appendChild ($ text1 );
$ Nextitem3-> appendChild ($ text2 );
$ Nextitem1-> appendChild ($ text );
}
Echo $ objDom-> saveXML ();
}
Simplexml_load_string converts an xml string to a string
$ String = <
Forty What?
Joe
Jane
I know thats the answer -- but whats the question?
XML;
$ Xml = simplexml_load_string ($ string );
Var_dump ($ xml );
?>
This script will display:
SimpleXMLElement Object
(
[Title] => Forty What?
[From] => Joe
[To] => Jane
[Body] =>
I know thats the answer -- but whats the question?
)
If you want to convert xml to an array, first convert it to a string containing key values, and then loop it into an array,
/**
* Convert xml to an array
* @ Param unknown_type $ xml
*/
Private function xml_to_array ($ xml)
{
$ Array = (array) (simplexml_load_string ($ xml, SimpleXMLElement, LIBXML_NOCDATA ));
Foreach ($ array as $ key => $ item ){
$ Array [$ key] = $ this-> struct_to_array (array) $ item );
}
Return $ array;
}
Private function struct_to_array ($ item ){
If (! Is_string ($ item )){
$ Item = (array) $ item;
Foreach ($ item as $ key => $ val ){
$ Item [$ key] = self: struct_to_array ($ val );
}
}
Return $ item;
}
Templates, function madexml () {// get template information $ strTempInfo = $ this-modelCmsObj-get...