• 技术文章 >php教程 >PHP源码

    将PHP数组转成XML

    PHP中文网PHP中文网2016-05-25 17:15:29原创399
    这是一个封装好的PHP类,用来将数组数据转成XML数据

    class ArrayToXML
    {
    	/**
    	 * The main function for converting to an XML document.
    	 * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
    	 *
    	 * @param array $data
    	 * @param string $rootNodeName - what you want the root node to be - defaultsto data.
    	 * @param SimpleXMLElement $xml - should only be used recursively
    	 * @return string XML
    	 */
    	public static function toXml($data, $rootNodeName = 'data', $xml=null)
    	{
    		// turn off compatibility mode as simple xml throws a wobbly if you don't.
    		if (ini_get('zend.ze1_compatibility_mode') == 1)
    		{
    			ini_set ('zend.ze1_compatibility_mode', 0);
    		}
    		
    		if ($xml == null)
    		{
    			$xml = simplexml_load_string("");
    		}
    		
    		// loop through the data passed in.
    		foreach($data as $key => $value)
    		{
    			// no numeric keys in our xml please!
    			if (is_numeric($key))
    			{
    				// make string key...
    				$key = "unknownNode_". (string) $key;
    			}
    			
    			// replace anything not alpha numeric
    			$key = preg_replace('/[^a-z]/i', '', $key);
    			
    			// if there is another array found recrusively call this function
    			if (is_array($value))
    			{
    				$node = $xml->addChild($key);
    				// recrusive call.
    				ArrayToXML::toXml($value, $rootNodeName, $node);
    			}
    			else 
    			{
    				// add single node.
                                    $value = htmlentities($value);
    				$xml->addChild($key,$value);
    			}
    			
    		}
    		// pass back as string. or simple xml object if you want!
    		return $xml->asXML();
    	}
    }
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:将PHP数组转成XML
    上一篇:字符串之模式匹配 下一篇:php实现的日历程序_php技巧
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• 极简的创建文件夹函数 • PHP一个敏感信息过滤思路• php对多维数组的某个键值排序方法• 检测移动设备的php代码(手机访问)
    1/1

    PHP中文网