1、使用类
注意: user.csv 第一行默认为数组的键, 且第一行不会被打印; (区别于下面的普通函数方法 )
例如:
name age gender
zhang 23 male
li 20 female
结果:
Array
(
[0] => Array
(
[name] => zhang
[age] => 23
[gender] => male
)
[1] => Array
(
[name] => li
[age] => 20
[gender] => female
)
)
回到正题:
//ini_set('memory_limit', '-1'); // 如果csv比较大的话,可以添加。
/*
* $file : csv file
* $csvDataArr : header of csv table, eg: arary('name','sex','age') or array(0,1,2)
* $specialhtml : whether do you want to convert special characters to html entities ?
* $removechar : which type do you want to remove special characters in array keys, manual or automatical ?
* edit http://www.
*/
class csv_to_array
{
private $counter;
private $handler;
private $length;
private $file;
private $seprator;
private $specialhtml;
private $removechar = 'manual';
private $csvDataArr;
private $csvData = array();
function __construct($file = '', $csvDataArr = '', $specialhtml = true, $length = 1000, $seprator = ',')
{
$this->counter = 0;
$this->length = $length;
$this->file = $file;
$this->seprator = $seprator;
$this->specialhtml = $specialhtml;
$this->csvDataArr = is_array($csvDataArr) ? $csvDataArr : array();
$this->handler = fopen($this->file, "r");
}
function get_array()
{
$getCsvArr = array();
$csvDataArr = array();
while(($data = fgetcsv($this->handler, $this->length, $this->seprator)) != FALSE)
{
$num = count($data);
$getCsvArr[$this->counter] = $data;
$this->counter++;
}
if(count($getCsvArr) > 0)
{
$csvDataArr = array_shift($getCsvArr);
if($this->csvDataArr) $csvDataArr = $this->csvDataArr;
$counter = 0;
foreach($getCsvArr as $csvValue)
{
$totalRec = count($csvValue);
for($i = 0; $i < $totalRec ; $i++)
{
$key = $this->csvDataArr ? $csvDataArr[$i] : $this->remove_char($csvDataArr[$i]);
if($csvValue[$i]) $this->csvData[$counter][$key] = $this->put_special_char($csvValue[$i]);
}
$counter++;
}
}
return $this->csvData;
}
function put_special_char($value)
{
return $this->specialhtml ? str_replace()(array('&','" ','\'','<','>'),array('&','"',''','<','>'),$value) : $value;
}
function remove_char($value)
{
$result = $this->removechar == 'manual' ? $this->remove_char_manual($value) : $this->remove_char_auto($value);
return str_replace(' ','_',trim($result));
}
private function remove_char_manual($value)
{
return str_replace(array('&','"','\'','<','>','(',')','%'),'',trim($value));
}
private function remove_char_auto($str,$x=0)
{
$x==0 ? $str=$this->make_semiangle($str) : '' ;
eregi('[[:punct:]]',$str,$arr);
$str = str_replace($arr[0],'',$str);
return eregi('[[:punct:]]',$str) ? $this->remove_char_auto($str,1) : $str;
}
private function make_semiangle($str)
{
$arr = array('0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
'5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
'y' => 'y', 'z' => 'z',
'(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
'】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
'‘' => '[', '’' => ']', '{' => '{', '}' => '}', '《' => '<',
'》' => '>',
'%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',
':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',
';' => ',', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
'”' => '"', '’' => '`', '‘' => '`', '|' => '|', '〃' => '"',
' ' => ' ','$'=>'$','@'=>'@','#'=>'#','^'=>'^','&'=>'&','*'=>'*');
return strtr($str, $arr);
}
function __destruct(){
fclose($this->handler);
}
}
// example:
$csv = new csv_to_array('user.csv');
echo "<pre>"; print_r($csv->get_array()); echo "</pre>";
?>
2、使用一般函数
function csv_to_array($csv)
{
$len = strlen($csv);
$table = array();
$cur_row = array();
$cur_val = "";
$state = "first item";
for ($i = 0; $i < $len; $i++)
{
//sleep(1000);
$ch = substr($csv,$i,1);
if ($state == "first item")
{
if ($ch == '"') $state = "we're quoted hea";
elseif ($ch == ",") //empty
{
$cur_row[] = ""; //done with first one
$cur_val = "";
$state = "first item";
}
elseif ($ch == "\n")
{
$cur_row[] = $cur_val;
$table[] = $cur_row;
$cur_row = array();
$cur_val = "";
$state = "first item";
}
elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";
else
{
$cur_val .= $ch;
$state = "gather not quote";
}
}
elseif ($state == "we're quoted hea")
{
if ($ch == '"') $state = "potential end quote found";
else $cur_val .= $ch;
}
elseif ($state == "potential end quote found")
{
if ($ch == '"')
{
$cur_val .= '"';
$state = "we're quoted hea";
}
elseif ($ch == ',')
{
$cur_row[] = $cur_val;
$cur_val = "";
$state = "first item";
}
elseif ($ch == "\n")
{
$cur_row[] = $cur_val;
$table[] = $cur_row;
$cur_row = array();
$cur_val = "";
$state = "first item";
}
elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";
else
{
$cur_val .= $ch;
$state = "we're quoted hea";
}
}
elseif ($state == "wait for a line feed, if so close out row!")
{
if ($ch == "\n")
{
$cur_row[] = $cur_val;
$cur_val = "";
$table[] = $cur_row;
$cur_row = array();
$state = "first item";
}
else
{
$cur_row[] = $cur_val;
$table[] = $cur_row;
$cur_row = array();
$cur_val = $ch;
$state = "gather not quote";
}
}
elseif ($state == "gather not quote")
{
if ($ch == ",")
{
$cur_row[] = $cur_val;
$cur_val = "";
$state = "first item";
}
elseif ($ch == "\n")
{
$cur_row[] = $cur_val;
$table[] = $cur_row;
$cur_row = array();
$cur_val = "";
$state = "first item";
}
elseif ($ch == "\r") $state = "wait for a line feed, if so close out row!";
else $cur_val .= $ch;
}
}
return $table;
}
//pass a csv string, get a php array
// example:
$arr = csv_to_array(file_get_contents('user.csv'));
echo "<pre>"; print_r($arr); echo "</pre>"
?>
或者
$arrCSV = array();
// Open the CSV
if (($handle = fopen("user.csv", "r")) !==FALSE) {
// Set the parent array key to 0
$key = 0;
// While there is data available loop through unlimited times (0) using separator (,)
while (($data = fgetcsv($handle, 0, ",")) !==FALSE) {
// Count the total keys in each row
$c = count($data);
//Populate the array
for ($x=0;$x<$c;$x++) $arrCSV[$key][$x] = $data[$x];
$key++;
} // end while
// Close the CSV file
fclose($handle);
} // end if
echo "<pre>"; print_r($arrCSV); echo "</pre>";
?>
至于哪种更好用,看自己的实际需求与个人爱好了,实际工作中csv转array的需求还是不少,建议大家多练习,多掌握。
假设:
http://cdn.//uploads/2011/06/1309476244-elicium-rai-01-528x351.jpg
假设这是一张防盗链的图片,直接打开时无法显示真实图片(除chrome浏览器外)。
解决方法如下所示。
1、使用iframe的方法
<iframe id="imiframe" src="javascript:parent.sc" scrolling="no" frameborder="0" onload="javascript:var x=document.getElementById('imiframe').contentWindow.document.images[0];this.width=x.width+10;this.height=x.height+10;"></iframe>
2、curl的方法
用法:
3、PHP header发送各种类型文件下载
文件名:showpic.php
$url = $_GET["url"];
//$url = str_replace()("http:/","http://",$url);
$dir = pathinfo($url);
$host = $dir['dirname'];
$refer = $host.'/';
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_REFERER, $refer);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//激活可修改页面,Activation can modify the page
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$ext = strtolower()(substr(strrchr($img,'.'),1,10));
$types = array(
'gif'=>'image/gif',
'jpeg'=>'image/jpeg',
'jpg'=>'image/jpeg',
'jpe'=>'image/jpeg',
'png'=>'image/png',
);
$type = $types[$ext] ? $types[$ext] : 'image/jpeg';
header("Content-type: ".$type);
echo $data;
?>
遇到PHP 提示错误Cannot modify header information headers already sent ,原因在于:这些代码之前不要有任何内容输出的,包括空白,切记!
有了以上的代码,就可以这样显示图片了:
真是道高一尺,魔高一丈啊,php图片防盗链就这样没有守住防线,哈哈。
PHP字符串自动填充、自动补全的方法介绍。
方法一:
定义和用法
sprintf()() 函数把格式化的字符串写写入一个变量中。
语法
sprintf(format,arg1,arg2,arg++)
参数 描述
format 必需。转换格式。
arg1 必需。规定插到 format 字符串中第一个 % 符号处的参数。
arg2 可选。规定插到 format 字符串中第二个 % 符号处的参数。
arg++ 可选。规定插到 format 字符串中第三、四等等 % 符号处的参数。
说明
参数 format 是转换的格式,以百分比符号 ("%") 开始到转换字符结束。下面的可能的 format 值:
%% - 返回百分比符号
%b - 二进制数
%c - 依照 ASCII 值的字符
%d - 带符号十进制数
%e - 可续计数法(比如 1.5e+3)
%u - 无符号十进制数
%f - 浮点数(local settings aware)
%F - 浮点数(not local settings aware)
%o - 八进制数
%s - 字符串
%x - 十六进制数(小写字母)
%X - 十六进制数(大写字母)
arg1, arg2, ++ 等参数将插入到主字符串中的百分号 (%) 符号处。该函数是逐步执行的。在第一个 % 符号中,插入 arg1,在第二个 % 符号处,插入 arg2,依此类推。
例1,
$str = "Hello";
$number = 123;
$txt = sprintf("%s world. Day number %u",$str,$number);
echo $txt; //Hello world. Day number 123
?>
例2,
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f<br />With no decimals: %1\$u",$number);
echo $txt;
//With 2 decimals: 123.00
//With no decimals: 123
?>
例3,
$number = 1;
$txt = sprintf('%02s', $number);
echo $txt; //01 by www.
?>
“%02s ”表示输出成长度为2的字符串或数字,如果长度不足,左边以零补全;如果写成 “%2s ”,则默认以空格补全;如果希望使用其它字符补全,则要在该字符前加上单引号,即形如“%'#2s ”的表示以井号补全;最后,如果希望补全发生在 字符串右边,则在百分号后加上减号,“%-02s ”。
参考:http://www./w3school/php/func_string_sprintf.html