/**
* XML encoding
* @param mixed $data data
* @param string $root root node name
* @param a sub-node name for a string $item numeric index
* @param string $attr root node properties
* @param string $id Numeric index child node key conversion property name
* @param string $encoding data encoding
* @return String
*/
Function xml_encode ($data, $root = ' think ', $item = ' item ', $attr = ', $id = ' id ', $encoding = ' Utf-8 ') { if (Is_array ($attr)) { $_ Attr = array (); foreach ($attr as $key => $value) { $_attr[ ] = "{$key}=\" {$value}\ ""; } $attr = implode (' ', $_attr);//implode - converts the value of a one-dimensional array to a string } $attr = trim ($attr); $attr = empty ($attr) ? " : " {$attr} "; $xml = "<?xml version=\" 1.0\ " encoding=\" {$encoding}\ "?>";// \" means escape double quotes $xml .= " <{$root} {$attr}> ";//$ attr root Node Properties $xml .= data_to_xml ($data, $item, $id); $xml .= "</{$root}>"; return $xml;} Function data_to_xml ($data, $item = ' item ', $id = ' id ') { $xml = $attr = '; foreach ($data as $key => $val) { if (Is_numeric ($key)) { $id && $attr = " {$id}=\" {$key}\ ""; $key = $item; } $xml .= "<{$key} {$attr}>"; $xml .= (Is_array ($val) | | is_object ($val)) ? data_to_xml ($val, $item, $id) : $val; $xml .= "</{$key}>"; } return $xml;} $data = array ( ' note ' =>array ( ' from ' + ' liming ', ' to ' = ' Xiaowang ', ' message ' = ' hello,world! ' ), $a =xml_encode ($data); Var_dump ($a);
The result of the execution is:
String ' <?xml version= "1.0" encoding= "Utf-8"?> <think> <note> <from> ;liming</from> <to>xiaowang</to> <message>hello,world!</message> </note> </think> ' (length=133)
Note: The result format is manually adjusted for easy reading!
This article is from the "11400485" blog, please be sure to keep this source http://11410485.blog.51cto.com/11400485/1833531
thinkphp Source Learning Xml_encode function data into XML format