您好,欢迎访问一九零五行业门户网

PHP中数组转换为XML格式_PHP教程

最近公司要做一个api接口,输出格式要有json与xml格式, 在php中,输入json直接json_encode就可以,但输出xml没有提供函数,于是决定自己写一个。formatoutput = true; } /** * 转换数组到xml * * @param array $array 要转换的数组 * @param string $rootname 要节点名称 * @param string $version 版本号 * @param string $encoding xml编码 * * @return string */ public static function parse($array, $rootname = 'root', $version = '1.0', $encoding = 'utf-8') { self::init($version, $encoding); //转换 $node = self::convert($array, $rootname); self::$doc->appendchild($node); return self::$doc->savexml(); } /** * 递归转换 * * @param array $array 数组 * @param string $nodename 节点名称 * * @return object (domelement) */ private static function convert($array, $nodename) { if (!is_array($array)) return false; //创建父节点 $node = self::createnode($nodename); //循环数组 foreach ($array as $key => $value) { $element = self::createnode($key); //如果不是数组,则创建节点的值 if (!is_array($value)) { $element->appendchild(self::createvalue($value)); $node->appendchild($element); } else { //如果是数组,则递归 $node->appendchild(self::convert($value, $key, $element)); } } return $node; } private static function createnode($name) { $node = null; //如果是字符串,则创建节点 if (!is_numeric($name)) { $node = self::$doc->createelement($name); } else { //如果是数字,则创建默认item节点 $node = self::$doc->createelement('item'); } return $node; } /** * 创建文本节点 * * @param string || bool || integer $value * * @return object (domtext || domcdatasection ); */ private static function createvalue($value) { $textnode = null; //如果是bool型,则转换为字符串 if (true === $value || false === $value) { $textnode = self::$doc->createtextnode($value ? 'true' : 'false'); } else { //如果含有html标签,则创建cdata节点 if (strpos($value, ' -1) { $textnode = self::$doc->createcdatasection($value); } else { $textnode = self::$doc->createtextnode($value); } } return $textnode; }}
http://www.bkjia.com/phpjc/477156.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/477156.htmltecharticle最近公司要做一个api接口,输出格式要有json与xml格式, 在php中,输入json直接json_encode就可以,但输出xml没有提供函数,于是决定自己写一...
其它类似信息

推荐信息