preface

This article’s custom function, mainly said some data conversion, not shrimp nonsense, directly to the business, I will continue to write some PHP development of some practical custom functions, convenient to use friends, can quickly develop and use.

Convert the XML format to an array

When we request some third party interface, either return you json type data format, or XML or other, if it is JSON, it is very convenient to use directly, when encountered XML format, you need to convert to array format, easy to use.

/** * Convert XML format to array *@paramString $XML XML string *@return mixed
 */
function xml_to_array($xml = ' ')
{
    // Use the function simplexml_load_string() to load an XML string into an object
    $obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    // Encode the object and then decode it to get the array
    $arr = json_decode(json_encode($obj), true);
    return $arr;
}
Copy the code

Hide the middle four digits of the phone number

Usually, for the sake of security and privacy protection, key information such as the user’s mobile phone number cannot be fully exposed to the public display on the interface, so it needs to be dealt with, such as hiding the middle four digits…

/** * The middle four digits of the hidden mobile phone number are **** *@paramString $mobile Normal mobile number *@return mixed
 */
function replace_phone($mobile = ' ')
{
    $new_mobile = substr_replace($mobile, '* * * *'.3.4);
    return $new_mobile;
}
Copy the code

The simplest API requests a common return data format

Here, I’ll explain the most simple, general API request, the most basic request return data format, usually, can be subdivided into successful failure and return back, everyone can be dealt with according to the actual situation, in a lot of framework, has directly encapsulation good method, you can also go to look at is how to deal with in the framework.

/** * The simplest Ajax request returns data format *@paramString $MSG Returns a message *@paramInt $code returns the identifier *@paramArray $data Returns data */
function ajax_return($msg = ' ', $code = 0, $data = [])
{
    $return['code'] = $code;
    $return['msg'] = $msg;
    $return['data'] = $data;
    exit(json_encode($return, JSON_UNESCAPED_UNICODE));
}
Copy the code

Intercept string

Usually, within the scope of some list or fixed, according to a certain length of string, if we don’t control, is likely to lead to more than display interface, or overflow, cause not beautiful page layout, etc., this time, we need to control show that the length of the string, some of the intercept out beyond…

/** * intercepts the string, and displays the excess with ellipsis *@paramString $text String to be intercepted *@paramInt $length Specifies the interception length. By default, all intercepts are *@paramString $rep intercepts the string beyond the replacement. The default is an ellipsis *@return string
 */
function cut_string($text = ' ', $length = 0, $rep = '... ')
{
    if (!empty($length) && mb_strlen($text, 'utf8') > $length) {
        $text = mb_substr($text, 0, $length, 'utf8') . $rep;
    }
    return $text;
}
Copy the code

Calculate age according to birthday

In some BBS or dating platform, often see so-and-so age 18, if when you meet this kind of development needs, also have to deal with, I’m a good developer, this kind of thing, I must help think about and let me go, arrangement, has been written, you can use them directly.

/** * Age is calculated according to birthday *@paramString $date Date of birthday *@return int
 */
function get_age($date = ' ')
{
    $age = 0;
    $time = strtotime($date);
    // If the date is illegal, it is not processed
    if(! $time) {return $age;
    }
    // Calculate the time difference between year, month and day
    $date = date('Y-m-d', $time);
    list($year, $month, $day) = explode("-", $date);
    $age = date("Y", time()) - $year;
    $diff_month = date("m") - $month;
    $diff_day = date("d") - $day;
    // Age under one year minus 1
    if ($age < 0 || $diff_month < 0 || $diff_day < 0) {
        $age--;
    }
    return $age;
}
Copy the code

Date and time display format conversion

The most common, we brush the life of wechat circle of friends every day, the time in the lower left corner, such as: 10 minutes ago, 2 hours ago, yesterday, etc., have you also encountered this kind of time display conversion demand, this kind of development demand to find me ah, I have arranged, use the kind of oh…

/** * Datetime display format conversion *@paramInt $time Timestamp *@return bool|string
 */
function transfer_show_time($time = 0)
{
    // Time display format
    $day_time = date("m-d H:i", $time);
    $hour_time = date("H:i", $time);
    / / time
    $diff_time = time() - $time;
    $date = $day_time;
    if ($diff_time < 60) {
        $date = 'just';
    } else if ($diff_time < 60 * 60) {
        $min = floor($diff_time / 60);
        $date = $min . 'Minutes ago';
    } else if ($diff_time < 60 * 60 * 24) {
        $h = floor($diff_time / (60 * 60));
        $date = $h . 'Hours ago' . $hour_time;
    } else if ($diff_time < 60 * 60 * 24 * 3) {
        $day = floor($diff_time / (60 * 60 * 24));
        if ($day == 1) {
            $date = 'yesterday' . $day_time;
        } else {
            $date = 'the day before yesterday. $day_time; }}return $date;
}
Copy the code

Get milliseconds

In daily development, we usually get the timestamp seconds directly from time(). It is rare to encounter the need to get the milliseconds, but be prepared if there is a need for this. As a professional developer, it is usually available on request…

/** * get the number of milliseconds *@return string
 */
function get_millisecond(a)
{
    list($t1, $t2) = explode(' ', microtime());
    $ms = sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    return $ms;
}
Copy the code

CURL request GET method

Often, we will encounter requests for third-party interfaces, and we will generally encapsulate our own interface request methods, which is the most basic GET request encapsulation

/** * CURL CURL *@paramString $URL Request interface address *@return bool|mixed
 */
function curl_get($url = ' ')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // Do not verify SSL certificates.
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}
Copy the code

CURL indicates the POST mode of a request

A lot of third-party interfaces are generally POST, so I also encapsulated a basic request method for you, you can modify and improve according to their own actual situation.

/** * delete from CURL@paramString $URL Request interface address *@paramArray $data request parameter *@paramInt $timeout Specifies the timeout period *@return mixed
 */
function curl_post($url = ' ', $data = [], $timeout = 3000)
{
    $post_data = http_build_query($data, ' '.'&');
    header("Content-type:text/html; charset=utf-8");
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}
Copy the code

The last

I will gradually update other practical functions, if you have other fun, easy to use, welcome to share, we learn and exchange together. By the way, if there is something wrong or wrong, please point it out and I will try to improve it. Thank you.