Home Backend Development PHP Tutorial PHP instance method summary

PHP instance method summary

Dec 02, 2017 am 10:03 AM
php Summarize method

多种PHP常用的方法实例,同学们可以看看,学习学习这些PHP方法或者可以研究研究这些PHP实例,来掌握这样知识点。

PHPExcel 读取Excel

获取文本中首张图片地址

将图片保存到本地

返回JSON数据

var_dump 函数改写

图片转为base64格式

使用curl 实现get请求

使用curl 实现post请求

简单的xml转数组方法

Utf-8转统一码

字符串转统一编码

获取IP地址

创建随机字符串

根据生日获取年龄

根据经纬度计算距离 

PHPExcel 读取excel

function readExcel($filename, $encode = 'utf-8')
{
//    import("ORG.Util.PHPExcel.IOFactory");
    import("Org/Util/PHPExcel");
    if (strpos($filename, "xlsx")) {
        $objReader = PHPExcel_IOFactory::createReader('Excel2007');
    } else {
        $objReader = PHPExcel_IOFactory::createReader('Excel5');
    }
    $objReader->setReadDataOnly(true);

    $objPHPExcel = $objReader->load($filename);


    $objWorksheet = $objPHPExcel->getActiveSheet();
    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();

    $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    $excelData = array();
    for ($row = 1; $row <= $highestRow; $row++) {
        if ((string)$objWorksheet->getCellByColumnAndRow(0, $row)->getValue() == "") continue;
        for ($col = 0; $col < $highestColumnIndex; $col++) {
            $value = (string)$objWorksheet->getCellByColumnAndRow($col, 1)->getValue();
            if ($value == "") {
                continue;
            }
            $excelData[$row - 1][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
        }
    }
    return $excelData;
}
Copy after login

获取文本中首张图片地址

function getFirstPic($content){
    if(preg_match_all("/(src)=([\"|&#39;]?)([^ \"&#39;>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)){
        $str=$matches[3][0];
        if(preg_match(&#39;/\/ueditor\/php\/upload\/image/&#39;,$str)){
            return $str1=substr($str,6);
        }
    }
}
Copy after login


将图片保存到本地

function getImage($url,$save_dir=&#39;&#39;,$filename=&#39;&#39;,$type=1){
    if(trim($url)==&#39;&#39;){
        return array(&#39;file_name&#39;=>&#39;&#39;,&#39;save_path&#39;=>&#39;&#39;,&#39;error&#39;=>1);
    }
    if(trim($save_dir)==&#39;&#39;){
        $save_dir=&#39;./&#39;;
    }
    if(trim($filename)==&#39;&#39;){//保存文件名
        $ext = strrchr($url,&#39;.&#39;);
        if($ext!=&#39;.gif&#39;&&$ext!=&#39;.jpg&#39;){
            return array(&#39;file_name&#39;=>&#39;&#39;,&#39;save_path&#39;=>&#39;&#39;,&#39;error&#39;=>3);
        }
        $filename=time().$ext;
    }
    if(0!==strrpos($save_dir,&#39;/&#39;)){
        $save_dir.=&#39;/&#39;;
    }
    //创建保存目录
    if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
        return array(&#39;file_name&#39;=>&#39;&#39;,&#39;save_path&#39;=>&#39;&#39;,&#39;error&#39;=>5);
    }
    //获取远程文件所采用的方法
    if($type){
        $ch=curl_init();
        $timeout=5;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $img=curl_exec($ch);
        curl_close($ch);
    }
    else{
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
    }
    $size=strlen($img);
    echo $size;
    //文件大小
    $fp2=fopen($save_dir.$filename,&#39;a&#39;);
    fwrite($fp2,$img);
    fclose($fp2);
    unset($img,$url);
    return array(&#39;file_name&#39;=>$filename,&#39;save_path&#39;=>$save_dir.$filename,&#39;error&#39;=>0);
}
Copy after login

返回JSON数据

function show($status, $msg, $closeCurrent=false, $data=array()){
    $tmpArr = array(
        &#39;statusCode&#39; => $status,
        &#39;message&#39;    => $msg,
        &#39;closeCurrent&#39; => $closeCurrent,
    );
    $tmpArr = array_merge($tmpArr, $data);
    exit(json_encode($tmpArr));
}
Copy after login


var_dump 函数改写

function lyl_dump($content){
    header("Content-type:text/html;charset=utf-8");
    echo &#39;<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />&#39;;
    echo "<pre class="brush:php;toolbar:false">";
    var_dump($content);
    echo "<pre/>";
    die;
}
Copy after login


图片转为base64格式

function base64EncodeImage ($image_file) {
    if(!file_exists($image_file)){
        return false;
    }
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, &#39;r&#39;), filesize($image_file));
    $base64_image = chunk_split(base64_encode($image_data));
    return $base64_image;
}
Copy after login


使用curl 实现get请求

function httpGet($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); //这个是的ssl校验,需要验证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); //
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
Copy after login


使用curl 实现post 请求

function httpPost($url,$post_data){
    $curl = curl_init();
    $post_data = json_encode($post_data);
    curl_setopt($ch , CURLOPT_URL , $url);
    curl_setopt($ch , CURLOPT_HEADER , 0 );
    curl_setopt( $ch, CURLOPT_POST, 1);          //设置为POST方式
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch , CURLOPT_POSTFIELDS , $post_data);
    $rst = curl_exec( $ch );
    curl_close( $ch );
    return $rst;
}
Copy after login


简单的xml转数组方法

function simplexml_to_array($simplexml_obj, $array_tags = array(), $strip_white = 1)
{
    if ($simplexml_obj) {
        if (count($simplexml_obj) == 0)
            return $strip_white ? trim((string)$simplexml_obj) : (string)$simplexml_obj;
        $attr = array();
        foreach ($simplexml_obj as $k => $val) {
            if (!empty($array_tags) && in_array($k, $array_tags)) {
                $attr[] = simplexml_to_array($val, $array_tags, $strip_white);
            } else {
                $attr[$k] = simplexml_to_array($val, $array_tags, $strip_white);
            }
        }
        return $attr;
    }
    return FALSE;
}
Copy after login


Utf-8转统一码

function utf8_to_unicode($char)
{
    switch (strlen($char)) {
        case 1:
            return ord($char);
        case 2:
            $n = (ord($char[0]) & 0x3f) << 6;
            $n += ord($char[1]) & 0x3f;
            return $n;
        case 3:
            $n = (ord($char[0]) & 0x1f) << 12;
            $n += (ord($char[1]) & 0x3f) << 6;
            $n += ord($char[2]) & 0x3f;
            return $n;
        case 4:
            $n = (ord($char[0]) & 0x0f) << 18;
            $n += (ord($char[1]) & 0x3f) << 12;
            $n += (ord($char[2]) & 0x3f) << 6;
            $n += ord($char[3]) & 0x3f;
            return $n;
    }
}
Copy after login


字符串转统一编码

function str_to_unicode_word($str,$depart=&#39; &#39;)
{
    $arr = array();
    $str_len = mb_strlen($str,&#39;utf-8&#39;);
    for($i = 0;$i < $str_len;$i++)
    {
        $s = mb_substr($str,$i,1,&#39;utf-8&#39;);
        if($s != &#39; &#39; && $s != &#39; &#39;)
        {
            $arr[] = &#39;ux&#39;.utf8_to_unicode($s);
        }
    }
    return implode($depart,$arr);
}
Copy after login


获取IP地址

function getIP()
{
    static $realip;
    if (isset($_SERVER)) {
        if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
            $realip = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $realip = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if (getenv("HTTP_X_FORWARDED_FOR")) {
            $realip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_CLIENT_IP")) {
            $realip = getenv("HTTP_CLIENT_IP");
        } else {
            $realip = getenv("REMOTE_ADDR");
        }
    }
    return $realip;
}
Copy after login


创建随机字符串

function createNonceStr($length = 16)
{
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}
Copy after login


根据生日获取年龄

function get_age($birthday){
    if($birthday){
        list($y1,$m1,$d1) = explode("-",date("Y-m-d",$birthday));
        list($y2,$m2,$d2) = explode("-",date("Y-m-d",time()));
        $age = $y2-$y1;
        if(intval($m2.$d2) < intval($m1.$d1)) {$age -= 1;}
        return $age;
    }else{
        return "未知";
    }
}
Copy after login


根据经纬度计算距离

function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000; 
    $lat1 = ($lat1 * pi() ) / 180;
    $lng1 = ($lng1 * pi() ) / 180;
    $lat2 = ($lat2 * pi() ) / 180;
    $lng2 = ($lng2 * pi() ) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}
Copy after login

以上就是 所有的php 实例方法总结 内容,希望对同学们有帮助。

相关推荐:

实例比较php方法重载的两种方式

php方法调用模式与函数调用模式简例

php方法调用模式与函数调用模式简例_PHP教程

The above is the detailed content of PHP instance method summary. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

See all articles