class
ArrayUtility
{
/* *
* Convert array to xml tree
*
* @param array $array
* @param array $options
* @return string
* @example xmlize()
*/
public function xmlize( $array , $options )
{
$encoding = isset ( $options [ ' encoding ' ]) ? $options [ $encoding ] : ' utf-8 ' ;
$root = isset ( $options [ ' root ' ]) ? $options [ ' root ' ] : ' response ' ;
$xml = " < ?xml version="1.0" encoding="{$encoding}"?> < $root> ”;
$xml .= self::_xmlize($array);
$xml .= “”;
return $xml;
}
private function _xmlize($array)
{
$string = ”;
foreach($array as $key => $value)
{
$stag = is_numeric($key) ? “item id=”$key” " : $key ;
$etag = is_numeric ( $key ) ? “item” : $key ;
if ( is_array ( $value ))
{
$string .= “ < " . $stag . " > ” . self :: _xmlize( $value ) . “ ”;
}
else
{
$string .= “ < " . $stag . " > ” . $value . “ ”;
}
}
return $string ;
}
}
使用方法:
$api_data = array (
' status ' => ' 200 ' ,
' message ' => ' 成功 ' ,
' data ' => array (
' account ' => array (
0 => array (
' id ' => 15 ,
' plat ' => 1 ,
' pay_account ' => ' glemir@yahoo.cn '
) ,
1 => array (
' id ' => 16 ,
' plat ' => 2 ,
' pay_account ' => ' test@gmail.com
)
)
)
);
header( ' Content - Type : text / xml ' );
$arrayob = new ArrayUtility();
$xml = $arrayob->xmlize($api_data); //这里可以加上编码的参数,默认utf-8
echo $xml;
{
/* *
* Convert array to xml tree
*
* @param array $array
* @param array $options
* @return string
* @example xmlize()
*/
public function xmlize( $array , $options )
{
$encoding = isset ( $options [ ' encoding ' ]) ? $options [ $encoding ] : ' utf-8 ' ;
$root = isset ( $options [ ' root ' ]) ? $options [ ' root ' ] : ' response ' ;
$xml = " < ?xml version="1.0" encoding="{$encoding}"?> < $root> ”;
$xml .= self::_xmlize($array);
$xml .= “”;
return $xml;
}
private function _xmlize($array)
{
$string = ”;
foreach($array as $key => $value)
{
$stag = is_numeric($key) ? “item id=”$key” " : $key ;
$etag = is_numeric ( $key ) ? “item” : $key ;
if ( is_array ( $value ))
{
$string .= “ < " . $stag . " > ” . self :: _xmlize( $value ) . “ ”;
}
else
{
$string .= “ < " . $stag . " > ” . $value . “ ”;
}
}
return $string ;
}
}
使用方法:
$api_data = array (
' status ' => ' 200 ' ,
' message ' => ' 成功 ' ,
' data ' => array (
' account ' => array (
0 => array (
' id ' => 15 ,
' plat ' => 1 ,
' pay_account ' => ' glemir@yahoo.cn '
) ,
1 => array (
' id ' => 16 ,
' plat ' => 2 ,
' pay_account ' => ' test@gmail.com
)
)
)
);
header( ' Content - Type : text / xml ' );
$arrayob = new ArrayUtility();
$xml = $arrayob->xmlize($api_data); //这里可以加上编码的参数,默认utf-8
echo $xml;