首页 > 编程技术 > php

非常优秀 PHP JSON解析器程序

发布时间:2016-11-25 15:41

JSOND:一个更优的PHP JSON解析器我光说优秀也没有,下面我来给各位演示几个例子吧,这会你看了就知道是不是优秀了哦。

首先,我们先来看看性能测试数据:

 代码如下 复制代码

STR: {"i": 23, "array": [1, null, false, true, ["aha", "baba", 23, {"test": 23}]]}
JSON:  time for 100000 iterations: 0.238321
JSOND: time for 100000 iterations: 0.236436

STR: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
JSON:  time for 100000 iterations: 0.110764
JSOND: time for 100000 iterations: 0.134212

STR: {"a": 23.2234232}
JSON:  time for 100000 iterations: 0.078458
JSOND: time for 100000 iterations: 0.055479

STR: {"long-str": "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.", }
JSON:  time for 100000 iterations: 0.881429
JSOND: time for 100000 iterations: 0.118529

STR: ... json_encode($_SERVER)
JSON:  time for 100000 iterations: 4.341252
JSOND: time for 100000 iterations: 1.960814

可以看到在大数据量的时候jsond的速度比json快多了。

项目地址:

Github:https://github.com/bukka/php-jsond

PECL:http://pecl.php.net/package/jsond

根据自身情况,选择相应的安装方法,安装成功后,查看phpinfo:

 

非常优秀 PHP JSON解析器程序

使用方法:

 代码如下 复制代码

mixed jsond_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] );
string jsond_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] );
string jsond_last_error_msg ( void );
int jsond_last_error ( void );

在php中中有自定义函数可以帮我人判断IP地址,也有我们常用的正则函数来判断IP地址,下面我分别来给各位同学总结了验证IP地址的一些方法。

filter函数过滤ip地址的方法:

 代码如下 复制代码

echo filter_var("127.0.0.1","FILTER_VALIDATE_INT"); //返回true or false

例子。

判断是否是合法IP

 代码如下 复制代码

if(filter_var($ip, FILTER_VALIDATE_IP)) {
// it's valid
}
else {
// it's not valid
}

判断是否是合法的公共IPv4地址,192.168.1.1这类的私有IP地址将会排除在外

 代码如下 复制代码
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) {
// it's valid
}
else {
// it's not valid
}

判断是否是合法的IPv6地址

 代码如下 复制代码
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
// it's valid
}
else {
// it's not valid
}

判断是否是public IPv4 IP或者是合法的Public IPv6 IP地址

 代码如下 复制代码
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
// it's valid
}
else {
// it's not valid
}

简单的正则

preg_match("/d{1,3}.d{1,3}.d{1,3}.d{1,3}/");// 此方法没不精确,学最大为255.255.255.255 但这个只是验证格式了,如999.999.999.999也可以通过验证。

我们进入升级改进

 代码如下 复制代码

functionis_ip($gonten){ 
$ip=explode(”.”,$gonten); 
for($i=0;$i<count($ip);$i++) 

if($ip[$i]>255){ 
return(0); 


return ereg(”^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$”,$gonten); 
}

这样就符合我们的要求了

再介绍一种用判断ip地址:

 代码如下 复制代码


function matchip($q){
preg_match('/((25[0-5])|(2[0-4]d)|(1dd)|([1-9]d)|d)(.((25[0-5])|(2[0-4]d)|(1dd)|([1-9]d)|d)){3}/', $q, $matches);
return $matches[0];
}

$ipaddress = '201.103.2.2';
$iperror ='262.3.6.6';
$iptest = matchip( $ipaddress );
//当我们给matchip 的值为$ipaddress输出为201.103.2.2
//当我们给matchip的函数值为$iperror时,输出值为 62.3.6.6

if( $iptest )
{
 echo $iptest;
}
else
{
 echo 'www.111cn.net提示:你输的的ip地址有问题';
}

如果我们要判断访问网站的是手机用户还是PC用户我们只要获取用户的HTTP_USER_AGENT即可,我先介绍了一个通用的Mobile_Detect,后面两个例子是自己写的希望对各位有帮助。

php代码

 代码如下 复制代码

//使用实例

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile())

// Check for any tablet.
if($detect->isTablet())

// Check for any mobile device, excluding tablets.
if ($detect->isMobile() && !$detect->isTablet())

if ($detect->isMobile() && !$detect->isTablet())

// Alternative to $detect->isAndroidOS()
$detect->is('AndroidOS');

// Batch usage
foreach($userAgents as $userAgent){
  $detect->setUserAgent($userAgent);
  $isMobile = $detect->isMobile();
}

// Version check.
$detect->version('iPad'); // 4.3 (float)


php判断手机访问

 代码如下 复制代码

ua = strtolower($_SERVER['HTTP_USER_AGENT']);

$uachar = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mobile|wap)/i";

if(($ua == '' || preg_match($uachar, $ua))&& !strpos(strtolower($_SERVER['REQUEST_URI']),'wap'))
{
    $Loaction = 'wap/';

    if (!empty($Loaction))
    {
        ecs_header("Location: $Loactionn");

        exit;
    }

}

 

/** 
* 自定义 header 函数,用于过滤可能出现的安全隐患 

* @param   string  string  内容 

* @return  void 
**/ 
function ecs_header($string, $replace = true, $http_response_code = 0) 

    if (strpos($string, '../upgrade/index.php') === 0) 
    { 
        echo '<script type="text/javascript">window.location.href="' . $string . '";</script>'; 
    } 
    $string = str_replace(array("r", "n"), array('', ''), $string); 
 
    if (preg_match('/^s*location:/is', $string)) 
    { 
        @header($string . "n", $replace); 
 
        exit(); 
    } 
 
    if (emptyempty($http_response_code) || PHP_VERSION < '4.3') 
    { 
        @header($string, $replace); 
    } 
    else   www.111cn.net
    { 
        @header($string, $replace, $http_response_code); 
    } 

js代码

测试代码:

 代码如下 复制代码

var isIPhone = /iPhone/i.test(navigator.userAgent),
 isIPad = /iPad/i.test(navigator.userAgent),
 isAndroid = /android/i.test(navigator.userAgent);
var isIOS = isIPhone  || isIPad;
alert(
 "iPhone? "+isIPhone+"tr"+
 "iPad? "+isIPad+"tr"+
 "Android? "+isAndroid+"tr"+
 "iOS? "+isIOS
);

在PHP中,用你认为最简洁的方法把驼峰样式的字符串转换成下划线样式的字符串。例:输入是FooBar的话,输出则是foo_bar。

自己在看到这个问题的时候,想到的是用ASCII码来处理,没往万能的正则上去想。好吧,下面来看看答案:

答案1:

 代码如下 复制代码

$str = 'OpenAPI';

$length = mb_strlen($str);

$new = '';

for($i = 0; $i < $length; $i++)
{
 $num = ord($str[$i]);
 $pre = ord($str[$i - 1]);

 $new .= ($i != 0 && ($num >= 65 && $num <= 90) && ($pre >= 97 && $pre <= 122)) ? "_{$str[$i]}" : $str[$i];
} www.111cn.net

echo strtolower($new) . '<br>';

答案2:

 代码如下 复制代码

echo strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $str)).'<br>';

那反过来下划线分割字符串转换成驼峰式字符串怎么搞呢

 代码如下 复制代码

f = new File("d:/temp/t.txt")
if(f.exists()){
    f.eachLine{ line->
        line = line.trim()
        String[] elems = line.split('_')
        for(int i = 0; i < elems.length; i++){
            elems[i] = elems[i].toLowerCase()
            if(i != 0){
                String elem = elems[i]
                char first = elem[0] as char
                elems[i] = "" + (char)(first - 32) + elem.substring(1)
            }
        }
        println elems.join()
    }
}

Php多线程的使用,首先需要PHP5.3以上版本,并安装pthreads PHP扩展,可以使PHP真正的支持多线程,扩展如何安装请自行百度

PHP扩展下载:https://github.com/krakjoe/pthreads

PHP手册文档:http://php.net/manual/zh/book.pthreads.php

在安装好扩展之后,就可以运用多线程了,下面贴个通过搜索结果抓取百度网盘内容的代码:

 代码如下 复制代码

<?php
include 'include/CurlLoad.class.php'; // 引入读取库
/**
 * 多线程抓取内容
 * @param array $url 待抓取URL列表集合
 * @return 成功返回指定内容,失败返回NULL
 */
function vget($url) {
 $ret = BaiduSRLinksGet ( $url, 1 ); // 获取结果列表地址
 if ($ret != null) {
  if (array_key_exists ( "links", $ret )) {
   $infos = array ();
   $number = count ( $ret ['links'] );
   for($i = 0; $i < $number; $i ++) {//循环创建线程对象
    $thread_array [$i] = new baidu_thread_run ( $ret ['links'] [$i] );
    $thread_array [$i]->start ();
   }
   foreach ( $thread_array as $thread_array_key => $thread_array_value ) {//检查线程是否执行结束
    while ( $thread_array [$thread_array_key]->isRunning () ) {
     usleep ( 10 );
    }
    if ($thread_array [$thread_array_key]->join ()) {//如果执行结束,取出结果
     $temp = $thread_array [$thread_array_key]->data;
     if ($temp != null)
      $infos ['res'] [] = $temp;
    }
   }
   $infos ['pages'] = $ret ['pages'];
   $infos ['status'] = "1";
  } else
  $infos = null;
 } else
  $infos = null;
 return $infos;
}
/**
 * 获取百度搜索结果列表URL
 *
 * @param string $url
 *         搜索结果页URL
 * @param int $format
 *         默认$format=0,获取默认地址;$format=1获取跳转后真实地址
 * @return NULL multitype:array()
 */
function BaiduSRLinksGet($url, $format = 0) {
 $html = CurlLoad::HtmlGet ( $url ); // 获取页面
 if ($html == null)
  return null;
 try {
  preg_match_all ( "/"url":"(?<links>.*)"}/", $html, $rets ); // 搜索结果链接筛选
  if (! array_key_exists ( 'links', $rets )) // 如果数组中不包含Links键名,表示获取失败
   return null;
  $ret = array ();
  if ($format == 1) {
   $number = count ( $rets ['links'] );
   for($i = 0; $i < $number; $i ++) {
    $headr_temp = CurlLoad::Get_Headers ( $rets ['links'] [$i], 1 ); // 通过headr获取真实地址
    if (array_key_exists ( "Location", $headr_temp ))
     $ret ['links'] [$i] = $headr_temp ['Location'];
    else
     $ret ['links'] = $rets ['links'];
   }
  } else
   $ret ['links'] = $rets ['links'];
  preg_match_all ( '/href="?/s?wd=site%3Apan.baidu.com%20(?<url>.+?)&ie=utf-8">/', $html, $out );
  unset ( $out ['url'] [0] );
  $number = count ( $out ['url'] );
  for($i = 1; $i < $number; $i ++) {
   preg_match_all ( '/&pn=(.*)/', $out ['url'] [$i], $temp );
   $ret ['pages'] [$temp [1] [0] / 10] = base64_encode ( $out ['url'] [$i] );
  }
  return $ret;
 } catch ( Exception $e ) {
  WriteLog ( $e );
  return null;
 }
}
/**
 * 百度网盘资源信息获取
 *
 * @param string $url
 *         网盘资源页URL
 * @return NULL array
 */
function PanInfoGet($url) {
 $html = CurlLoad::HtmlGet ( $url ); // 获取页面
 if ($html == null)
  return null;
 try {
  if (preg_match_all ( "/文件名:(?<name>.*) 文件大小:(?<size>.*) 分享者:(?<user>.*) 分享时间:(?<date>.*) 下载次数:(?<number>[0-9]+)/", $html, $ret ) == 0)
   return null;
  $rets ['name'] = $ret ['name'] [0];
  $rets ['size'] = $ret ['size'] [0];
  $rets ['user'] = $ret ['user'] [0];
  $rets ['date'] = $ret ['date'] [0];
  $rets ['number'] = $ret ['number'] [0];
  $rets ['link'] = $url;
  return $rets;
 } catch ( Exception $e ) {
  WriteLog ( $e );
  return null;
 }
}
function WriteLog($str) {
 $file = fopen ( "../error.log", "a+" );
 fwrite ( $file, "Warning:" . date ( "Y/m/d H:i:s" ) . ":" . $str . "rn" );
 fclose ( $file );
}
/**
 * 多线程抓取对象
 * @author MuXi
 *
 */
class baidu_thread_run extends Thread {
 public $url;
 public $data;
 public function __construct($url) {
  $this->url = $url;
 }
 public function run() {
  if (($url = $this->url)) {
   $this->data = PanInfoGet ( $url );//线程执行方法
  }
 }
}
?>

标签:[!--infotagslink--]

您可能感兴趣的文章: