Php generates xml like a tree. you can add nodes one by one. you can add multiple subnodes under a parent node, functionmadexml () {// Obtain template information $ strTempInfo = $ this-modelCmsObj-getTemplate ('20140901'); $ arrTemp = explode (#, $ strTempI
Php generates xml like a tree, adding nodes one by one. you can add multiple subnodes under a parent node, function madexml ()
- {
- // Obtain template information
- $ StrTempInfo = $ this-> modelCmsObj-> getTemplate ('20140901 ');
- $ 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 that's the answer -- but what's 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 that's the answer -- but what's 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;
- }