PHP一些案例代码

发布于 2021-05-12 23:27 ,所属分类:区块连和PHP开发学习资料

刹客网络科技资讯
点击右侧,最新科技资讯!


正则提取域名

<?php//输出echo Matchurl("https://lanyou.vip/");   function Matchurl($param){  preg_match('/^http(s)?:\/\/(.*)\//U',$param,$url);  $value = str_replace(array('http://','https://','/'),"",$url[2]);  return $value;}



编写JSON数据并追加

<?的PHP//输出回声Write_log ($ _REQUEST [ 'pid' ]); / ***写入数据并追加* @return string $ array需要写入的元素* /函数Write_log ($ array ){   $ path =目录名(__FILE__ )。'/data.json' ;  如果(!file_exists ($ path )){    fopen ($ path ,“ a” );   }  $ Getfile = file_get_contents ($ path );  $ format = '[' 。rtrim ($ Getfile ,“,” )。']' ;   $ data = json_decode ($ format ,true );  $ query   =   array_filter ($ data ,function ($ vue )use ($ array ){       if ($ vue [ 'id' ] == $ array ){返回$ vue [ 'id' ] == $ array ;}    });  如果(!$ query ){    $ Insert = array ('id' => $ array );    $ myfile = fopen ($ path ,“ a” );     fwrite ($ myfile ,json_encode ($ Insert )。',' );    fclose ($ myfile );  }}



xml转JSON进阶版

通常XML转JSON的话只需用simplexml_load_string就可以了,但是有些项目就爬的时候可能会遇到GBK编码的。
遇到GBK编码的时候simplexml_load_string就会报错用不了,以下代码具有自动检测是否GBK编码并成功转JSON。

<?php//调用echo json_encode(xml($_REQUEST['url']),JSON_UNESCAPED_UNICODE); //xml转JSONfunction xml($url){    $api = Encod($url);    $str = str_replace(array("\n", "\r"), " ", $api);    preg_match('/encoding="(.*)"/U', $str, $match);    if ($match[1] == 'gbk') {        $html = str_replace("gbk", "UTF-8", $str);    } else {        $html = $str;    }    $xml = simplexml_load_string($html, 'SimpleXMLElement', LIBXML_NOCDATA);    $json = json_encode($xml, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);    $data = json_decode($json, true);    return $data;}//编码检测function Encod($url){    $api = file_get_contents($url);    $string = preg_match('/^.*$/u', $api) > 0;    if ($string == true) {        $value = $api;    } else {        $value = mb_convert_encoding($api, "UTF-8", "GBK");    }    return $value;}



实现获取顶级域名

echo get_host('lanyou.vip'); function Get_host($host_url){    $url   = $host_url ? $host_url : $_SERVER['HTTP_HOST'];  $data = explode('.', $url);    $count = count($data);    //判断是否是双后缀    $row = true;    $array = 'com.cn,net.cn,org.cn,gov.cn,ac.cn';    $cut_out = explode(',', $array);    foreach($cut_out as $value){        if(strpos($url,$value)){            $row = false;        }    }    //如果是返回FALSE ,如果不是返回true    if($row == true){        // 是否为当前域名        if($url == 'localhost'){            $value = $data[$count-1];        }else{            $value = $data[$count-2].'.'.$data[$count-1];        }    }else{        $value = $data[$count-3].'.'.$data[$count-2].'.'.$data[$count-1];    }       return $value;}

如果调用需要带上HTTP的话方法如下

$url = 'lanyou.vip'; preg_match("/^http(s)?:\/\/(.*?)\//",$url,$json);if($json[2]){  $data = $json[2];}else{  $data = $url;}echo get_host($data);




点分享


点收藏

点点赞

点在看




相关资源