用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - php代码库

输出格式化处理

2014-09-01 作者: 青剑举报

[php]代码库

<?php

final class out {

	/**
	* 数组输出的格式
	*/
	public function out_data($data,$type=null,$encode=null){
		$type = strtolower($type);
		
		if($encode && $encode!='UTF-8')
		$data = $this->iconvs($data,'GBK','UTF-8');
		
		$type = strtolower($type);
		
		if(!$type){
			if(!empty($_GET['out']))$type=$_GET['out'];
			else
			$type='json';
		}
		if($type=='json'){
			if(!headers_sent())
			header('Content-Type:application/json');
			echo json_encode($data);
		}elseif($type=='print'){
			if(!headers_sent())
			header("Content-type:text/html;Charset=utf-8");
			echo '<pre>';print_r($data);echo '</pre>';
		}elseif($type=='serialize'){
			if(!headers_sent())
			header("Content-type:text/html;Charset=utf-8");
			echo serialize($data);
		}elseif($type=='var_export'){
			if(!headers_sent())
			header("Content-type:text/html;Charset=utf-8");
			var_export($data);
		}elseif($type=='var_dump'){
			if(!headers_sent())
			header("Content-type:text/html;Charset=utf-8");
			var_dump($data);
		}elseif($type=='xml'){
			if(!headers_sent())
			header("Content-type:text/xml;Charset=utf-8");
			echo self::arrtoxml($data);		
		}else{
			if(!headers_sent())
			header("Content-type:text/html;Charset=utf-8");
			echo self::outtable($data);
		}
		exit();
	}
 
	public function arrtoxml($arr,$dom=0,$item=0){
		if (!$dom){
		$dom = new DOMDocument("1.0");
		}
		if(!$item){
		$item = $dom->createElement("root");
		$dom->appendChild($item);
		}
		foreach ($arr as $key=>$val){
			
			$itemx = $dom->createElement(is_string($key)?(is_numeric(substr($key,0,1))?'_'.$key:$key):"item");
			$item->appendChild($itemx);
			if (!is_array($val) && !is_object($val)){
				$text = $dom->createTextNode($val);
				$itemx->appendChild($text);
			}else {
				if(is_object($val)){
					
				}
				self::arrtoxml($val,$dom,$itemx);
			}
		}
		return $dom->saveXML();
	} 
	/**
	 * xml转换成数组
	 * @param type $contents
	 * @param type $get_attributes
	 * @param type $priority
	 * @return type 
	 */
	public function xml2array($contents, $get_attributes=1, $priority = 'tag') {
		if (!$contents)
			return array();
	
		if (!function_exists('xml_parser_create')) {
			//print "'xml_parser_create()' function not found!"; 
			return array();
		}
	
		//Get the XML parser of PHP - PHP must have this module for the parser to work 
		$parser = xml_parser_create('');
		xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
		xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
		xml_parse_into_struct($parser, trim($contents), $xml_values);
		xml_parser_free($parser);
	
		if (!$xml_values)
			return; //Hmm 
	
	
	
	
	
			
	//Initializations 
		$xml_array = array();
		$parents = array();
		$opened_tags = array();
		$arr = array();
	
		$current = &$xml_array; //Refference 
		//Go through the tags. 
		$repeated_tag_index = array(); //Multiple tags with same name will be turned into an array 
		foreach ($xml_values as $data) {
			unset($attributes, $value); //Remove existing values, or there will be trouble 
			//This command will extract these variables into the foreach scope 
			// tag(string), type(string), level(int), attributes(array). 
			extract($data); //We could use the array by itself, but this cooler. 
	
			$result = array();
			$attributes_data = array();
	
			if (isset($value)) {
				if ($priority == 'tag')
					$result = $value;
				else
					$result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
			}
	
			//Set the attributes too. 
			if (isset($attributes) and $get_attributes) {
				foreach ($attributes as $attr => $val) {
					if ($priority == 'tag')
						$attributes_data[$attr] = $val;
					else
						$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
				}
			}
	
			//See tag status and do the needed. 
			if ($type == "open") {//The starting of the tag '<tag>' 
				$parent[$level - 1] = &$current;
				if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag 
					$current[$tag] = $result;
					if ($attributes_data)
						$current[$tag . '_attr'] = $attributes_data;
					$repeated_tag_index[$tag . '_' . $level] = 1;
	
					$current = &$current[$tag];
				} else { //There was another element with the same tag name 
					if (isset($current[$tag][0])) {//If there is a 0th element it is already an array 
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
						$repeated_tag_index[$tag . '_' . $level]++;
					} else {//This section will make the value an array if multiple tags with the same name appear together 
						$current[$tag] = array($current[$tag], $result); //This will combine the existing item and the new item together to make an array 
						$repeated_tag_index[$tag . '_' . $level] = 2;
	
						if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well 
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
							unset($current[$tag . '_attr']);
						}
					}
					$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
					$current = &$current[$tag][$last_item_index];
				}
			} elseif ($type == "complete") { //Tags that ends in 1 line '<tag />' 
				//See if the key is already taken. 
				if (!isset($current[$tag])) { //New Key 
					$current[$tag] = $result;
					$repeated_tag_index[$tag . '_' . $level] = 1;
					if ($priority == 'tag' and $attributes_data)
						$current[$tag . '_attr'] = $attributes_data;
				} else { //If taken, put all things inside a list(array) 
					if (isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array 
						// push the new element into that array. 
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
	
						if ($priority == 'tag' and $get_attributes and $attributes_data) {
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
						}
						$repeated_tag_index[$tag . '_' . $level]++;
					} else { //If it is not an array 
						$current[$tag] = array($current[$tag], $result); //Make it an array using using the existing value and the new value 
						$repeated_tag_index[$tag . '_' . $level] = 1;
						if ($priority == 'tag' and $get_attributes) {
							if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well 
								$current[$tag]['0_attr'] = $current[$tag . '_attr'];
								unset($current[$tag . '_attr']);
							}
	
							if ($attributes_data) {
								$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
							}
						}
						$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken 
					}
				}
			} elseif ($type == 'close') { //End of tag '</tag>' 
				$current = &$parent[$level - 1];
			}
		}
	
		return($xml_array);
	}	
	
	/**
	 * 将數組输出为表格
	 * @param array $games 数组内容
	 * @param array $keys  数组标题,不指定则默认以数组KEY作为标题
	 * @param array $showTitle 是否显示标题
	 */
	public function outtable($games, $keys=null,$showTitle=true) {
		if($keys==null){
			if(!is_array($games) || count($games)<1){
				
				return print_r($games,true);
			}
			if(!$games[key($games)]){
				$echo .= 'Error Format';
				return;
			}
			if(is_array(current($games))){
				$keys = array_keys(current($games));
			}else{
				  $echo .= '<table  cellspacing="1" cellpadding="3" border="0" class="table0">';
				   $i = 0;
					foreach ($games as $game_id => $game) {
						$i++;
						$echo .= '<tr bgcolor="' . (($i % 2) ? "#EEEEEE" : '#FFFFFF') . '">';
						   $echo .= '<th align="right">'.$game_id.'</th>';
							$echo .= '<td>';
							if (is_array($game))
								$echo .= self::outtable($game);
							else
								$echo .= $game;
							$echo .= '</td>';
					
						$echo .= '</tr>';
					}
					$echo .= '</table>';
					return;
			}
		}
		if(!is_array($games)){
				return print_r($games,true);
		}
			
		$echo .= '<table  cellspacing="1" cellpadding="3" border="0" class="table0">';
		$echo .= '<tr id=head style="">';
	   if($showTitle){
			$echo .= '<th>key</th>';
			foreach ($keys as $k => $v) {
				$echo .= '<th>';
				$echo .= $v;
				$echo .= '</th>';
			}
			$echo .= '</tr>';
	   }    $i = 0;
		foreach ($games as $game_id => $game) {
			$i++;
	
			$echo .= '<tr bgcolor="' . (($i % 2) ? "#EEEEEE" : '#FFFFFF') . '">';
			if($showTitle)   $echo .= '<th>'.$game_id.'</th>';
			
			if(is_array($game)){
			foreach ($keys as $k => $v) {
				$echo .= '<td>';
				if (is_array($game[$v]))
					$echo .= self::outtable($game[$v],null,false);
				else
					$echo .= $game[$v];
				$echo .= '</td>';
			}
			}else{
				$echo .= '<td colspan="'.count($keys).'">';
					$echo .= $game;
				$echo .= '</td>';
			}
			
			$echo .= '</tr>';
		}
		$echo .= '</table>';
		return $echo ;
	}

	//一个切割函数
	public function cut($file, $from, $end) //字符串切割函数.
	{
		if(!$file)return $file;
	  $message = explode($from, $file);
	  if(count($message)>1)
	  $message = explode($end, $message[1]);
	  else return '';
	  return $message[0];
	
	}
	
	public function formatHTML($html){
			$html = preg_replace('/[\n\r\t]/', ' ', $html); 
			$html = preg_replace('/\s(?=\s)/', '', $html); 
			$html = str_replace('> ','>',$html);
			$html = str_replace(' <','<',$html);
			$html = str_replace(' > ','>',$html);
			return $html;	
	}

		//使用配置去采集内容		
	
	public function iconvs($var,$encode,$outcode){
		if(is_object($var) || is_array($var)){
			foreach($var as $k=>$v){
					unset($var[$k]);
					$var[iconv($encode,$outcode,$k)]=$this->iconvs($v,$encode,$outcode);
			}
		}else{
			$var =iconv($encode,$outcode,$var);
		}
		return $var;
	}
	
}

?>


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...