当前位置:Gxlcms > PHP教程 > PHP实例方法有哪些例子

PHP实例方法有哪些例子

时间:2021-07-01 10:21:17 帮助过:32人阅读

PHP实例方法的例子有:1、PHPExcel读取Excel,2、获取文本中首张图片地址;3、将图片保存到本地;4、返回JSON数据;5、【var_dump】函数改写;6、图片转为base64格式等等。

PHP实例方法的例子有:

  • PHPExcel 读取Excel

  • 获取文本中首张图片地址

  • 将图片保存到本地

  • 返回JSON数据

  • var_dump 函数改写

  • 图片转为base64格式

  • 使用curl 实现get请求

  • 使用curl 实现post请求

  • 简单的xml转数组方法

  • Utf-8转统一码

  • 字符串转统一编码

  • 获取IP地址

  • 创建随机字符串

  • 根据生日获取年龄

  • 根据经纬度计算距离

PHPExcel 读取excel

  1. function readExcel($filename, $encode = 'utf-8')
  2. {
  3. // import("ORG.Util.PHPExcel.IOFactory");
  4. import("Org/Util/PHPExcel");
  5. if (strpos($filename, "xlsx")) {
  6. $objReader = PHPExcel_IOFactory::createReader('Excel2007');
  7. } else {
  8. $objReader = PHPExcel_IOFactory::createReader('Excel5');
  9. }
  10. $objReader->setReadDataOnly(true);
  11. $objPHPExcel = $objReader->load($filename);
  12. $objWorksheet = $objPHPExcel->getActiveSheet();
  13. $highestRow = $objWorksheet->getHighestRow();
  14. $highestColumn = $objWorksheet->getHighestColumn();
  15. $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
  16. $excelData = array();
  17. for ($row = 1; $row <= $highestRow; $row++) {
  18. if ((string)$objWorksheet->getCellByColumnAndRow(0, $row)->getValue() == "") continue;
  19. for ($col = 0; $col < $highestColumnIndex; $col++) {
  20. $value = (string)$objWorksheet->getCellByColumnAndRow($col, 1)->getValue();
  21. if ($value == "") {
  22. continue;
  23. }
  24. $excelData[$row - 1][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
  25. }
  26. }
  27. return $excelData;
  28. }

获取文本中首张图片地址

  1. function getFirstPic($content){
  2. if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)){
  3. $str=$matches[3][0];
  4. if(preg_match('/\/ueditor\/php\/upload\/image/',$str)){
  5. return $str1=substr($str,6);
  6. }
  7. }
  8. }

将图片保存到本地

  1. function getImage($url,$save_dir='',$filename='',$type=1){
  2. if(trim($url)==''){
  3. return array('file_name'=>'','save_path'=>'','error'=>1);
  4. }
  5. if(trim($save_dir)==''){
  6. $save_dir='./';
  7. }
  8. if(trim($filename)==''){//保存文件名
  9. $ext = strrchr($url,'.');
  10. if($ext!='.gif'&&$ext!='.jpg'){
  11. return array('file_name'=>'','save_path'=>'','error'=>3);
  12. }
  13. $filename=time().$ext;
  14. }
  15. if(0!==strrpos($save_dir,'/')){
  16. $save_dir.='/';
  17. }
  18. //创建保存目录
  19. if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
  20. return array('file_name'=>'','save_path'=>'','error'=>5);
  21. }
  22. //获取远程文件所采用的方法
  23. if($type){
  24. $ch=curl_init();
  25. $timeout=5;
  26. curl_setopt($ch,CURLOPT_URL,$url);
  27. curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  28. curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  29. $img=curl_exec($ch);
  30. curl_close($ch);
  31. }
  32. else{
  33. ob_start();
  34. readfile($url);
  35. $img=ob_get_contents();
  36. ob_end_clean();
  37. }
  38. $size=strlen($img);
  39. echo $size;
  40. //文件大小
  41. $fp2=fopen($save_dir.$filename,'a');
  42. fwrite($fp2,$img);
  43. fclose($fp2);
  44. unset($img,$url);
  45. return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
  46. }

返回JSON数据

  1. function show($status, $msg, $closeCurrent=false, $data=array()){
  2. $tmpArr = array(
  3. 'statusCode' => $status,
  4. 'message' => $msg,
  5. 'closeCurrent' => $closeCurrent,
  6. );
  7. $tmpArr = array_merge($tmpArr, $data);
  8. exit(json_encode($tmpArr));
  9. }

var_dump 函数改写

  1. function lyl_dump($content){
  2. header("Content-type:text/html;charset=utf-8");
  3. echo '<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />';
  4. echo "<pre>";
  5. var_dump($content);
  6. echo "<pre/>";
  7. die;
  8. }

图片转为base64格式

  1. function base64EncodeImage ($image_file) {
  2. if(!file_exists($image_file)){
  3. return false;
  4. }
  5. $image_info = getimagesize($image_file);
  6. $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
  7. $base64_image = chunk_split(base64_encode($image_data));
  8. return $base64_image;
  9. }

使用curl 实现get请求

  1. function httpGet($url) {
  2. $curl = curl_init();
  3. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  4. curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  5. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); //这个是的ssl校验,需要验证
  6. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); //
  7. curl_setopt($curl, CURLOPT_URL, $url);
  8. $res = curl_exec($curl);
  9. curl_close($curl);
  10. return $res;
  11. }

使用curl 实现post 请求

  1. function httpPost($url,$post_data){
  2. $curl = curl_init();
  3. $post_data = json_encode($post_data);
  4. curl_setopt($ch , CURLOPT_URL , $url);
  5. curl_setopt($ch , CURLOPT_HEADER , 0 );
  6. curl_setopt( $ch, CURLOPT_POST, 1); //设置为POST方式
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  8. curl_setopt($ch , CURLOPT_POSTFIELDS , $post_data);
  9. $rst = curl_exec( $ch );
  10. curl_close( $ch );
  11. return $rst;
  12. }

简单的xml转数组方法

  1. function simplexml_to_array($simplexml_obj, $array_tags = array(), $strip_white = 1)
  2. {
  3. if ($simplexml_obj) {
  4. if (count($simplexml_obj) == 0)
  5. return $strip_white ? trim((string)$simplexml_obj) : (string)$simplexml_obj;
  6. $attr = array();
  7. foreach ($simplexml_obj as $k => $val) {
  8. if (!empty($array_tags) && in_array($k, $array_tags)) {
  9. $attr[] = simplexml_to_array($val, $array_tags, $strip_white);
  10. } else {
  11. $attr[$k] = simplexml_to_array($val, $array_tags, $strip_white);
  12. }
  13. }
  14. return $attr;
  15. }
  16. return FALSE;
  17. }

Utf-8转统一码

  1. function utf8_to_unicode($char)
  2. {
  3. switch (strlen($char)) {
  4. case 1:
  5. return ord($char);
  6. case 2:
  7. $n = (ord($char[0]) & 0x3f) << 6;
  8. $n += ord($char[1]) & 0x3f;
  9. return $n;
  10. case 3:
  11. $n = (ord($char[0]) & 0x1f) << 12;
  12. $n += (ord($char[1]) & 0x3f) << 6;
  13. $n += ord($char[2]) & 0x3f;
  14. return $n;
  15. case 4:
  16. $n = (ord($char[0]) & 0x0f) << 18;
  17. $n += (ord($char[1]) & 0x3f) << 12;
  18. $n += (ord($char[2]) & 0x3f) << 6;
  19. $n += ord($char[3]) & 0x3f;
  20. return $n;
  21. }
  22. }

字符串转统一编码

  1. function str_to_unicode_word($str,$depart=' ')
  2. {
  3. $arr = array();
  4. $str_len = mb_strlen($str,'utf-8');
  5. for($i = 0;$i < $str_len;$i++)
  6. {
  7. $s = mb_substr($str,$i,1,'utf-8');
  8. if($s != ' ' && $s != ' ')
  9. {
  10. $arr[] = 'ux'.utf8_to_unicode($s);
  11. }
  12. }
  13. return implode($depart,$arr);
  14. }

获取IP地址

  1. function getIP()
  2. {
  3. static $realip;
  4. if (isset($_SERVER)) {
  5. if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
  6. $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
  7. } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
  8. $realip = $_SERVER["HTTP_CLIENT_IP"];
  9. } else {
  10. $realip = $_SERVER["REMOTE_ADDR"];
  11. }
  12. } else {
  13. if (getenv("HTTP_X_FORWARDED_FOR")) {
  14. $realip = getenv("HTTP_X_FORWARDED_FOR");
  15. } else if (getenv("HTTP_CLIENT_IP")) {
  16. $realip = getenv("HTTP_CLIENT_IP");
  17. } else {
  18. $realip = getenv("REMOTE_ADDR");
  19. }
  20. }
  21. return $realip;
  22. }

创建随机字符串

  1. function createNonceStr($length = 16)
  2. {
  3. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  4. $str = "";
  5. for ($i = 0; $i < $length; $i++) {
  6. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  7. }
  8. return $str;
  9. }

根据生日获取年龄

  1. function get_age($birthday){
  2. if($birthday){
  3. list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthday));
  4. list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
  5. $age = $y2-$y1;
  6. if(intval($m2.$d2) < intval($m1.$d1)) {$age -= 1;}
  7. return $age;
  8. }else{
  9. return "未知";
  10. }
  11. }

根据经纬度计算距离

  1. function getDistance($lat1, $lng1, $lat2, $lng2)
  2. {
  3. $earthRadius = 6367000;
  4. $lat1 = ($lat1 * pi() ) / 180;
  5. $lng1 = ($lng1 * pi() ) / 180;
  6. $lat2 = ($lat2 * pi() ) / 180;
  7. $lng2 = ($lng2 * pi() ) / 180;
  8. $calcLongitude = $lng2 - $lng1;
  9. $calcLatitude = $lat2 - $lat1;
  10. $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
  11. $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
  12. $calculatedDistance = $earthRadius * $stepTwo;
  13. return round($calculatedDistance);
  14. }

相关免费学习推荐:php编程(视频)

以上就是PHP实例方法有哪些例子的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行