首页 > 编程技术 > php

一个简单的php+Ajax购物车程序代码(1/2)

发布时间:2016-11-25 17:28

本文章来给大家推荐一个不错的购物车效果,这里主要求包括了几个东西,一个是购物车类用php写的, 还有一个Ajax操作用到了jquery,还有一个jquery插件thickbox了,下面我们来看看。

购物车类:shop_cart.php
购物车的操作:cart_action.php
首页:index.html
Ajax操作用到了jquery,还有一个jquery插件thickbox

不多说了你可以先看看效果示例
shop_cart.php当然是购物车的核心,但是这个类很简单,因为他又引进了cart_action.php用于对外操作。所以这个类显得相当精简。
购物车类shop_cart.php

 代码如下 复制代码

cart_name = $name;
$this->items = $_SESSION[$this->cart_name];
}

/**
* setItemQuantity() - Set the quantity of an item.
*
* @param string $order_code The order code of the item.
* @param int $quantity The quantity.
*/
function setItemQuantity($order_code, $quantity) {
$this->items[$order_code] = $quantity;
}

/**
* getItemPrice() - Get the price of an item.
*
* @param string $order_code The order code of the item.
* @return int The price.
*/
function getItemPrice($order_code) {
// This is where the code taht retrieves prices
// goes. We'll just say everything costs $9.99 for this tutorial.
return 9.99;
}

/**
* getItemName() - Get the name of an item.
*
* @param string $order_code The order code of the item.
*/
function getItemName($order_code) {
// This is where the code that retrieves product names
// goes. We'll just return something generic for this tutorial.
return 'My Product (' . $order_code . ')';
}

/**
* getItems() - Get all items.
*
* @return array The items.
*/
function getItems() {
return $this->items;
}

/**
* hasItems() - Checks to see if there are items in the cart.
*
* @return bool True if there are items.
*/
function hasItems() {
return (bool) $this->items;
}

/**
* getItemQuantity() - Get the quantity of an item in the cart.
*
* @param string $order_code The order code.
* @return int The quantity.
*/
function getItemQuantity($order_code) {
return (int) $this->items[$order_code];
}

/**
* clean() - Cleanup the cart contents. If any items have a
*           quantity less than one, remove them.
*/
function clean() {
foreach ( $this->items as $order_code=>$quantity ) {
if ( $quantity < 1 )     unset($this->items[$order_code]);
}
}

/**
* save() - Saves the cart to a session variable.
*/
function save() {
$this->clean();
$_SESSION[$this->cart_name] = $this->items;
}
}

?>

对于cart_action,他实现了shop_cart类与index的中间作用,用于更新,删除,增加商品的操作。
cart_action.php

 代码如下 复制代码

getItemQuantity($_GET['order_code'])+$_GET['quantity'];
$Cart->setItemQuantity($_GET['order_code'], $quantity);
}else{

if ( !empty($_GET['quantity']) ) {
foreach ( $_GET['quantity'] as $order_code=>$quantity){
$Cart->setItemQuantity($order_code, $quantity);
}
}

if ( !empty($_GET['remove']) ) {
foreach ( $_GET['remove'] as $order_code ) {
$Cart->setItemQuantity($order_code, 0);
}
}
}
$Cart->save();

header('Location: cart.php');

?>

还有就是index.html实现对外的操作,也就是添加操作

 代码如下 复制代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<title>Shopping Cart</title>
<script" width=100% src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script" width=100% src="js/jquery.color.js" type="text/javascript"></script>
<script" width=100% src="js/thickbox.js" type="text/javascript"></script>
<script" width=100% src="js/cart.js" type="text/javascript"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/thickbox.css" rel="stylesheet" type="text/css" media="screen" />

<script type="text/javascript">
$(function() {
$("form.cart_form").submit(function() {
var title = "Your Shopping Cart";
var orderCode = $("input[name=order_code]", this).val();
var quantity = $("input[name=quantity]", this).val();
var url = "cart_action.php?order_code=" + orderCode + "&amp;amp;amp;amp;amp;amp;amp;quantity=" + quantity + "&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780";
tb_show(title, url, false);

return false;
});
});
</script>
</head>
<body>
<div id="container">
<h1>购物车</h1>
<a href="cart.php?KeepThis=true&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780" title="Your Shopping Cart" class="thickbox">打开购物车</a>
<hr />
<a href="cart_action.php?order_code=KWL-JFE&amp;amp;amp;amp;amp;amp;amp;quantity=3&amp;amp;amp;amp;amp;amp;amp;TB_iframe=true&amp;amp;amp;amp;amp;amp;amp;height=400&amp;amp;amp;amp;amp;amp;amp;width=780" title="Your Shopping Cart" class="thickbox">添加三个 KWL-JFE 到购物车</a>
<hr />
<form class="cart_form" action="cart_action.php" method="get">
<input type="hidden" name="order_code" value="KWL-JFE" />
<label>KWL-JFE: <input class="center" type="text" name="quantity" value="1" size="3" ?></label>
<input type="submit" name="submit" value="添加到购物车" />
</form>
</div>
</body>
</html>

还有就是cart.php这是我们的购物车

 代码如下 复制代码
<?php
include('shopping_cart.class.php');
session_start();
$Cart = new Shopping_Cart('shopping_cart');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
<head>
<title>Shopping Cart</title>
<script" width=100% src="js/jquery-1.2.6.pack.js" type="text/javascript"></script>
<script" width=100% src="js/jquery.color.js" type="text/javascript"></script>
<script" width=100% src="js/cart.js" type="text/javascript"></script>
<link href="css/cart.css" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div id="container">
<h1>Shopping Cart</h1>
<?php if ( $Cart->hasItems() ) : ?>
<form action="cart_action.php" method="get">
<table id="cart">
<tr>
<th>数量</th>
<th>商品名称</th>
<th>商品编号</th>
<th>单价</th>
<th>总价</th>
<th>删除</th>
</tr>
<?php
$total_price = $i = 0;
foreach ( $Cart->getItems() as $order_code=>$quantity ) :
$total_price += $quantity*$Cart->getItemPrice($order_code);
?>
<?php echo $i++%2==0 ? "<tr>" : "<tr class='odd'>"; ?>
<td class="quantity center"><input type="text" name="quantity[<?php echo $order_code; ?>]" size="3" value="<?php echo $quantity; ?>" tabindex="<?php echo $i; ?>" /></td>
<td class="item_name"><?php echo $Cart->getItemName($order_code); ?></td>
<td class="order_code"><?php echo $order_code; ?></td>
<td class="unit_price">$<?php echo $Cart->getItemPrice($order_code); ?></td>
<td class="extended_price">$<?php echo ($Cart->getItemPrice($order_code)*$quantity); ?></td>
<td class="remove center"><input type="checkbox" name="remove[]" value="<?php echo $order_code; ?>" /></td>
</tr>
<?php endforeach; ?>
<tr><td colspan="2"></td><td  colspan="3" id="total_price">您的消费总金额是:¥<?php echo $total_price; ?></td></tr>
</table>
<input type="submit" name="update" value="保存购物车" />
</form>
<?php else: ?>
<p class="center">您还没有购物.</p>
<?php endif; ?>
<p><a href="load.php">加载简单的购物车</a></p>
</div>
</body>
</html>

在php中下载文件我们用得最多的是直接使用readfile()函数,readfile()可以实现把服务器源文件给下载,下面我来给大家介绍readfile下载文件的方法与性能介绍

例1

 代码如下 复制代码

<?php
header(“Content-Type: text/html; charset=UTF-8″);
header(“Content-type:application/text”);

// 文件将被称为 downloaded.pdf
header(“Content-Disposition:attachment;filename=log.text”);

// PDF 源在 original.pdf 中
readfile(“ptindex_user_profilebasc.html”);

?>

例2

 代码如下 复制代码

 

 $item=trim($_GET['fileName']).".txt";  
    $abs_item='/usr/home/文件夹名称/文件夹名称/文件夹名称/'.$item;  
    $browser='IE';  
    header('Content-Type: '.(($browser=='IE' || $browser=='OPERA')?  
        'application/octetstream':'application/octet-stream'));  
    header('Expires: '.gmdate('D, d M Y H:i:s').' GMT');  
    header('Content-Transfer-Encoding: binary');  
    header('Content-Length: '.filesize($abs_item));  
    if($browser=='IE') {  
        header('Content-Disposition: attachment; filename="'.$item.'"');  
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');  
        header('Pragma: public');  
    } else {  
        header('Content-Disposition: attachment; filename="'.$item.'"');  
        header('Cache-Control: no-cache, must-revalidate');  
        header('Pragma: no-cache');  
    }  
@readfile($abs_item); 

上面只能下载本地函数,如果要下载远程的我们可以如下操作PHP远程下载文件到本地的函数

 代码如下 复制代码

<?php

echo httpcopy("/baidu_sylogo1.gif");

function httpcopy($url, $file="", $timeout=60) {
    $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
    $dir = pathinfo($file,PATHINFO_DIRNAME);
    !is_dir($dir) && @mkdir($dir,0755,true);
    $url = str_replace(" ","%20",$url);

    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $temp = curl_exec($ch);
        if(@file_put_contents($file, $temp) && !curl_error($ch)) {
            return $file;
        } else {
            return false;
        }
    } else {
        $opts = array(
            "http"=>array(
            "method"=>"GET",
            "header"=>"",
            "timeout"=>$timeout)
        );
        $context = stream_context_create($opts);
        if(@copy($url, $file, $context)) {
            //$http_response_header
            return $file;
        } else {
            return false;
        }
    }
}
?>

最后分享一个支持多种文件下载的类函数

 代码如下 复制代码

<?php
/**
 * 使用方法:
 * require_once 'download.class.php';
 * $filepath = './path/filename.html';
 * $downname = 'downname.html';
 * $down = new download($filepath,$downname);
 * 或
 * $down = new download();
 *
 * */
class download
{
 var $filepath;
 var $downname;
 var $ErrInfo;
 var $is_attachment = false;
 var $_LANG = array(
   'err' => '错误',
   'args_empty' => '参数错误。',
   'file_not_exists' => '文件不存在!',
   'file_not_readable' => '文件不可读!',
  );
 var $MIMETypes = array(
   'ez' => 'application/andrew-inset',
   'hqx' => 'application/mac-binhex40',
   'cpt' => 'application/mac-compactpro',
   'doc' => 'application/msword',
   'bin' => 'application/octet-stream',
   'dms' => 'application/octet-stream',
   'lha' => 'application/octet-stream',
   'lzh' => 'application/octet-stream',
   'exe' => 'application/octet-stream',
   'class' => 'application/octet-stream',
   'so' => 'application/octet-stream',
   'dll' => 'application/octet-stream',
   'oda' => 'application/oda',
   'pdf' => 'application/pdf',
   'ai' => 'application/postscrīpt',
   'eps' => 'application/postscrīpt',
   'ps' => 'application/postscrīpt',
   'smi' => 'application/smil',
   'smil' => 'application/smil',
   'mif' => 'application/vnd.mif',
   'xls' => 'application/vnd.ms-excel',
   'ppt' => 'application/vnd.ms-powerpoint',
   'wbxml' => 'application/vnd.wap.wbxml',
   'wmlc' => 'application/vnd.wap.wmlc',
   'wmlsc' => 'application/vnd.wap.wmlscrīptc',
   'bcpio' => 'application/x-bcpio',
   'vcd' => 'application/x-cdlink',
   'pgn' => 'application/x-chess-pgn',
   'cpio' => 'application/x-cpio',
   'csh' => 'application/x-csh',
   'dcr' => 'application/x-director',
   'dir' => 'application/x-director',
   'dxr' => 'application/x-director',
   'dvi' => 'application/x-dvi',
   'spl' => 'application/x-futuresplash',
   'gtar' => 'application/x-gtar',
   'hdf' => 'application/x-hdf',
   'js' => 'application/x-javascrīpt',
   'skp' => 'application/x-koan',
   'skd' => 'application/x-koan',
   'skt' => 'application/x-koan',
   'skm' => 'application/x-koan',
   'latex' => 'application/x-latex',
   'nc' => 'application/x-netcdf',
   'cdf' => 'application/x-netcdf',
   'sh' => 'application/x-sh',
   'shar' => 'application/x-shar',
   'swf' => 'application/x-shockwave-flash',
   'sit' => 'application/x-stuffit',
   'sv4cpio' => 'application/x-sv4cpio',
   'sv4crc' => 'application/x-sv4crc',
   'tar' => 'application/x-tar',
   'tcl' => 'application/x-tcl',
   'tex' => 'application/x-tex',
   'texinfo' => 'application/x-texinfo',
   'texi' => 'application/x-texinfo',
   't' => 'application/x-troff',
   'tr' => 'application/x-troff',
   'roff' => 'application/x-troff',
   'man' => 'application/x-troff-man',
   'me' => 'application/x-troff-me',
   'ms' => 'application/x-troff-ms',
   'ustar' => 'application/x-ustar',
   'src' => 'application/x-wais-source',
   'xhtml' => 'application/xhtml+xml',
   'xht' => 'application/xhtml+xml',
   'zip' => 'application/zip',
   'au' => 'audio/basic',
   'snd' => 'audio/basic',
   'mid' => 'audio/midi',
   'midi' => 'audio/midi',
   'kar' => 'audio/midi',
   'mpga' => 'audio/mpeg',
   'mp2' => 'audio/mpeg',
   'mp3' => 'audio/mpeg',
   'wma' => 'audio/mpeg',
   'aif' => 'audio/x-aiff',
   'aiff' => 'audio/x-aiff',
   'aifc' => 'audio/x-aiff',
   'm3u' => 'audio/x-mpegurl',
   'ram' => 'audio/x-pn-realaudio',
   'rm' => 'audio/x-pn-realaudio',
   'rpm' => 'audio/x-pn-realaudio-plugin',
   'ra' => 'audio/x-realaudio',
   'wav' => 'audio/x-wav',
   'pdb' => 'chemical/x-pdb',
   'xyz' => 'chemical/x-xyz',
   'bmp' => 'image/bmp',
   'gif' => 'image/gif',
   'ief' => 'image/ief',
   'jpeg' => 'image/jpeg',
   'jpg' => 'image/jpeg',
   'jpe' => 'image/jpeg',
   'png' => 'image/png',
   'tiff' => 'image/tiff',
   'tif' => 'image/tiff',
   'djvu' => 'image/vnd.djvu',
   'djv' => 'image/vnd.djvu',
   'wbmp' => 'image/vnd.wap.wbmp',
   'ras' => 'image/x-cmu-raster',
   'pnm' => 'image/x-portable-anymap',
   'pbm' => 'image/x-portable-bitmap',
   'pgm' => 'image/x-portable-graymap',
   'ppm' => 'image/x-portable-pixmap',
   'rgb' => 'image/x-rgb',
   'xbm' => 'image/x-xbitmap',
   'xpm' => 'image/x-xpixmap',
   'xwd' => 'image/x-xwindowdump',
   'igs' => 'model/iges',
   'iges' => 'model/iges',
   'msh' => 'model/mesh',
   'mesh' => 'model/mesh',
   'silo' => 'model/mesh',
   'wrl' => 'model/vrml',
   'vrml' => 'model/vrml',
   'css' => 'text/css',
   'html' => 'text/html',
   'htm' => 'text/html',
   'asc' => 'text/plain',
   'txt' => 'text/plain',
   'rtx' => 'text/richtext',
   'rtf' => 'text/rtf',
   'sgml' => 'text/sgml',
   'sgm' => 'text/sgml',
   'tsv' => 'text/tab-separated-values',
   'wml' => 'text/vnd.wap.wml',
   'wmls' => 'text/vnd.wap.wmlscrīpt',
   'etx' => 'text/x-setext',
   'xsl' => 'text/xml',
   'xml' => 'text/xml',
   'mpeg' => 'video/mpeg',
   'mpg' => 'video/mpeg',
   'mpe' => 'video/mpeg',
   'qt' => 'video/quicktime',
   'mov' => 'video/quicktime',
   'mxu' => 'video/vnd.mpegurl',
   'avi' => 'video/x-msvideo',
   'movie' => 'video/x-sgi-movie',
   'wmv' => 'application/x-mplayer2',
   'ice' => 'x-conference/x-cooltalk',
  );
 
 function download($filepath='',$downname='')
 {
  if($filepath == '' AND !$this->filepath)
  {
   $this->ErrInfo = $this->_LANG['err'] . ':' . $this->_LANG['args_empty'];
   return false;
  }
  if($filepath == '') $filepath = $this->filepath;
  if(!file_exists($filepath))
  {
   $this->ErrInfo = $this->_LANG['err'] . ':' . $this->_LANG['file_not_exists'];
   return false;
  }
  if($downname == '' AND !$this->downname) $downname = $filepath;
  if($downname == '') $downname = $this->downname;
  // 文件扩展名
  $fileExt = substr(strrchr($filepath, '.'), 1);
  // 文件类型
  $fileType = $this->MIMETypes[$fileExt] ? $this->MIMETypes[$fileExt] : 'application/octet-stream';
  // 是否是图片
  $isImage = False;
  /*
  简述: getimagesize(), 详见手册
  说明: 判定某个文件是否为图片的有效手段, 常用在文件上传验证
  */
  $imgInfo = @getimagesize($filepath);
  if ($imgInfo[2] && $imgInfo['bits'])
  {
   $fileType = $imgInfo['mime'];  // 支持不标准扩展名
   $isImage = True;
  }
  // 显示方式
  if($this->is_attachment)
  {
   $attachment = 'attachment';  // 指定弹出下载对话框
  }
  else
  {
   $attachment = $isImage ? 'inline' : 'attachment';
  }
  // 读取文件
  if (is_readable($filepath))
  {
   /*
   简述: ob_end_clean() 清空并关闭输出缓冲, 详见手册
   说明: 关闭输出缓冲, 使文件片段内容读取至内存后即被送出, 减少资源消耗
   */
   ob_end_clean();
   /*
   HTTP头信息: 指示客户机可以接收生存期不大于指定时间(秒)的响应
   */
   header('Cache-control: max-age=31536000');
   /*
   HTTP头信息: 缓存文件过期时间(格林威治标准时)
   */
   header('Expires: ' . gmdate('D, d M Y H:i:s', time()+31536000) . ' GMT');
   /*
   HTTP头信息: 文件在服务期端最后被修改的时间
   Cache-control,Expires,Last-Modified 都是控制浏览器缓存的头信息
   在一些访问量巨大的门户, 合理的设置缓存能够避免过多的服务器请求, 一定程度下缓解服务器的压力
   */
   header('Last-Modified: ' . gmdate('D, d M Y H:i:s' , filemtime($filepath) . ' GMT'));
   /*
   HTTP头信息: 文档的编码(Encode)方法, 因为附件请求的文件多样化, 改变编码方式有可能损坏文件, 故为none
   */
   header('Content-Encoding: none');
   /*
   HTTP头信息: 告诉浏览器当前请求的文件类型.
   1.始终指定为application/octet-stream, 就代表文件是二进制流, 始终提示下载.
   2.指定对应的类型, 如请求的是mp3文件, 对应的MIME类型是audio/mpeg, IE就会自动启动Windows Media Player进行播放.
   */
   header('Content-type: ' . $fileType);
   /*
   HTTP头信息: 如果为attachment, 则告诉浏览器, 在访问时弹出”文件下载”对话框, 并指定保存时文件的默认名称(可以与服务器的文件名不同)
   如果要让浏览器直接显示内容, 则要指定为inline, 如图片, 文本
   */
   header('Content-Disposition: ' . $attachment . '; filename=' . $downname);
   /*
   HTTP头信息: 告诉浏览器文件长度
   (IE下载文件的时候不是有文件大小信息么?)
   */
   header('Content-Length: ' . filesize($filepath));
   // 打开文件(二进制只读模式)
   $fp = fopen($filepath, 'rb');
   // 输出文件
   fpassthru($fp);
   // 关闭文件
   fclose($fp);
   return true;
  }
  else
  {
   $this->ErrInfo = $this->_LANG['err'] . ':' . $this->_LANG['file_not_readable'];
   return false;
  }
 }
}
?>

php 创建文件的方法有很多种我们最常用的就是fopen,file_put_contents这两种方法来创建文件了,下面我来给大家详细介绍介绍,有需要了解的同学可参考。

创建php文件

 代码如下 复制代码

<?php
$str="<?php echo 123;?>";
file_put_contents('test.php',$str);//使用脚本创建一个php文件
?>

例2

 代码如下 复制代码

<?php
if ($argc != 2) {
die("Usage: php mkphp.php filename");
}
array_shift($argv);
$cat= $argv[0];
file_put_contents($cat.".php", "<?php

?>");

利用fopen创建文件

 代码如下 复制代码

<?

$fp=fopen("1.txt","w+");//fopen()的其它开关请参看相关函数
$str="我加我加我加加加";
fputs($fp,$str);
fclose($fp);
?>

上面没作任何考虑,如果要全面点我们首先,确定你所要新建文件所在的目录权限; 建议设备为777。然后,新建文件的名称建议使用绝对路径。

 代码如下 复制代码

<?php
$filename="test.txt";
$fp=fopen("$filename", "w+"); //打开文件指针,创建文件
if ( !is_writable($filename) ){
      die("文件:" .$filename. "不可写,请检查!");
}
//fwrite($filename, "anything you want to write to $filename.";
fclose($fp);  //关闭指针

'r' 开文件方式为只读,文件指’指到开始处
'r+' 开文件方式为可读写,文件指’指到开始处
'w' 开文件方式为写入,文件指’指到开始处 并将原文‘的长度设为 0。若文件不存在‘‘建立新文件–
'w+' 开文件方式为可读写,文件指’指到开始处 并将原文‘的长度设为 0。若文件不存在‘‘建立新文件–
'a' 开文件方式为写入,文件指’指到文件最后。若文件不存在‘‘建立新文件–
'a+' 开文件方式为可读写,文件指’指到文件最后。若文件不存在‘‘建立新文件–
'b' 若操作系统的文字及二进位文件不同,‘可以用“‘”,UNIX 系统不–要“用 参”。

 代码如下 复制代码

///创建文件
function creat_file($PATH){
   $sFile = "test.html";
   if (file_exists($PATH.$sFile)) {
    creat_file();
   } else {
    $fp= fopen($PATH.$sFile,"w");
    fclose($fp);
   }
   return $sFile;
}

页面执行时间计算也只是一个大概的过程,我们把程序计算程序的初始化函数放在页面最顶部,然后把计算函数放页面最底部,然后当页面执行完成就可以计算出相关值了,下面看实例

具体代码

 代码如下 复制代码

<?php
class runtime
{
    var $StartTime = 0;
    var $StopTime = 0;
 
    function get_microtime()
    {
        list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }
 
    function start()
    {
        $this->StartTime = $this->get_microtime();
    }
 
    function stop()
    {
        $this->StopTime = $this->get_microtime();
    }
 
    function spent()
    {
        return round(($this->StopTime - $this->StartTime) * 1000, 1);
    }
 
}
 
 
//例子
$runtime= new runtime;
$runtime->start();
 
//你的代码开始
 
$a = 0;
for($i=0; $i<1000000; $i++)
{
    $a += $i;
}
 
//你的代码结束
 
$runtime->stop();
echo "页面执行时间: ".$runtime->spent()." 毫秒";
?>


调用方法上面有介绍了我就不说了,我们只是要注意$runtime->start();与$runtime->spent()必须,一前一后哦,否则是无效的,还有不能放在缓存页面中和html页面中。

本文章来给大家介绍php反中文汉字转Unicode编码实现程序方法,有需要了解的朋友可进入参考。

程序

 代码如下 复制代码

/**
 * $str 原始字符串
 * $encoding 原始字符串的编码,默认GBK
 * $prefix 编码后的前缀,默认"&#"
 * $postfix 编码后的后缀,默认";"
 */
function unicode_encode($str, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
    $str = iconv($encoding, 'UCS-2', $str);
    $arrstr = str_split($str, 2);
    $unistr = '';
    for($i = 0, $len = count($arrstr); $i < $len; $i++) {
        $dec = hexdec(bin2hex($arrstr[$i]));
        $unistr .= $prefix . $dec . $postfix;
    }
    return $unistr;
}
 
/**
 * $str Unicode编码后的字符串
 * $encoding 原始字符串的编码,默认GBK
 * $prefix 编码字符串的前缀,默认"&#"
 * $postfix 编码字符串的后缀,默认";"
 */
function unicode_decode($unistr, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
    $arruni = explode($prefix, $unistr);
    $unistr = '';
    for($i = 1, $len = count($arruni); $i < $len; $i++) {
        if (strlen($postfix) > 0) {
            $arruni[$i] = substr($arruni[$i], 0, strlen($arruni[$i]) - strlen($postfix));
        }
        $temp = intval($arruni[$i]);
        $unistr .= ($temp < 256) ? chr(0) . chr($temp) : chr($temp / 256) . chr($temp % 256);
    }
    return iconv('UCS-2', $encoding, $unistr);
}

使用范例:

 代码如下 复制代码

//GBK字符串测试
$str = '<b>哈哈</b>';
echo $str.'<br />';
 
$unistr = unicode_encode($str);
echo $unistr.'<br />'; // &#60;&#98;&#62;&#21704;&#21704;&#60;&#47;&#98;&#62;
 
$str2 = unicode_decode($unistr);
echo $str2.'<br />'; //<b>哈哈</b>
 
//UTF-8字符串测试
$utf8_str = iconv('GBK', 'UTF-8', $str);
echo $utf8_str.'<br />'; // <b>????</b> 注:UTF在GBK下显示的乱码!可切换浏览器的编码测试
 
$utf8_unistr = unicode_encode($utf8_str, 'UTF-8');
echo $utf8_unistr.'<br />'; // &#60;&#98;&#62;&#21704;&#21704;&#60;&#47;&#98;&#62;
 
$utf8_str2 = unicode_decode($utf8_unistr, 'UTF-8');
echo $utf8_str2.'<br />'; // <b>????</b>
 
//其它后缀、前缀测试
$prefix_unistr = unicode_encode($str, 'GBK', "\u", '');
echo $prefix_unistr.'<br />'; // u60u98u62u21704u21704u60u47u98u62
 
$profix_unistr2 = unicode_decode($prefix_unistr, 'GBK', "\u", '');
echo $profix_unistr2.'<br />'; //<b>哈哈</b>

标签:[!--infotagslink--]

您可能感兴趣的文章: