The function of csv import in php

Maybe the current method is not perfect


<?php 
$file = $_FILES['csv'];

if ($file['error'] != 0)
{
	$this->show_warning('select_file');
	return;
}

$data = import_from_csv($file['tmp_name'], false, 'utf-8', 'utf-8');
$parents = array(0 => 0); // 存放layer的parent的数组
$fileds = array_intersect($data[0],array('cate_name', 'sort_order', 'if_show')); //第一行含有的字段
$start_col = intval(array_search('cate_name', $fileds)); //主数据区开始列号
print_r($data);
				
/**
 * 从csv文件导入
 *
 * @param string $filename 文件名
 * @param bool $header 是否有标题行,如果有标题行,从第二行开始读数据
 * @param string $from_charset 源编码
 * @param string $to_charset 目标编码
 * @param string $delimiter 分隔符
 * @return array
 */
function import_from_csv($filename, $header = true, $from_charset = '', $to_charset = '', $delimiter= ',')
{
	if ($from_charset && $to_charset && $from_charset != $to_charset)
	{
		$need_convert = true;
	}
	else
	{
		$need_convert = false;
	}

	$data = array();
	$handle = fopen($filename, "r");
	while (($row = fgetcsv($handle, 100000, $delimiter)) !== FALSE) {
		if ($need_convert)
		{
			foreach ($row as $key => $col)
			{
				$row[$key] = iconv($from_charset, $to_charset, $col);    // 20121020 陈胜国 使用 ICONV 做字符集转换
			}
		}
		$data[] = $row;
	}
	fclose($handle);

	if ($header && $data)
	{
		array_shift($data);
	}

	return addslashes_deep($data);
}

/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashes_deep($value)
{
	if (empty($value))
	{
		return $value;
	}
	else
	{
		return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
	}
}
?>


{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324124339&siteId=291194637