`
flex_莫冲
  • 浏览: 1075771 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
查詢重複數據的sql sql, mysql 查询同一表内多字段同时重复记录的SQL语句
 


查询同一表内多字段同时重复记录的SQL语句 
来自:7th string 


比如现在有一人员表  (表名:peosons) 
若想将姓名、身份证号、住址这三个字段完全相同的记录查询出来 select   p1.*   from   persons   p1,persons   p2   where   p1.id<>p2.id   and   p1.cardid   =   p2.cardid   and   p1.pname   =   p2.pname   and   p1.address   =   p2.address 
可以实现上述效果. 
几个删除重复记录的SQL语句 
   
1.用rowid方法 
2.用group by方法 
3.用distinct方法 
   
1。用rowid方法 
据据Oracle带的rowid属性,进行判断,是否存在重复,语句如下: 
查数据: 
     select * from table1 a where rowid !=(select   max(rowid)   
     from table1 b where a.name1=b.name1 and a.name2=b.name2......) 
删数据: 
    delete   from table1 a where rowid !=(select   max(rowid)   
     from table1 b where a.name1=b.name1 and a.name2=b.name2......) 
2.group by方法 
查数据: 
  select count(num), max(name) from student --列出重复的记录数,并列出他的name属性 
  group by num 
  having count(num) >1 --按num分组后找出表中num列重复,即出现次数大于一次 
删数据: 
  delete from student 
  group by num 
  having count(num) >1 
  这样的话就把所有重复的都删除了。 
3.用distinct方法 -对于小的表比较有用 
create table table_new as   select distinct *   from table1 minux 
truncate table table1; 
insert into table1 select * from table_new; 


查询及删除重复记录的方法大全 

1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断 
select * from people 
where peopleId in (select  peopleId  from  people  group  by  peopleId  having  count(peopleId) > 1) 


2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录 
delete from people 
where peopleId  in (select  peopleId  from people  group  by  peopleId   having  count(peopleId) > 1) 
and rowid not in (select min(rowid) from  people  group by peopleId  having count(peopleId )>1) 


3、查找表中多余的重复记录(多个字段) 
select * from vitae a 
where (a.peopleId,a.seq) in  (select peopleId,seq from vitae group by peopleId,seq  having count(*) > 1) 


4、删除表中多余的重复记录(多个字段),只留有rowid最小的记录 
delete from vitae a 
where (a.peopleId,a.seq) in  (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) 
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1) 


5、查找表中多余的重复记录(多个字段),不包含rowid最小的记录 
select * from vitae a 
where (a.peopleId,a.seq) in  (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1) 
and rowid not in (select min(rowid) from vitae group by peopleId,seq having count(*)>1) 


(二) 
比方说 
在A表中存在一个字段“name”, 
而且不同记录之间的“name”值有可能会相同, 
现在就是需要查询出在该表中的各记录之间,“name”值存在重复的项; 
Select Name,Count(*) From A Group By Name Having Count(*) > 1 
如果还查性别也相同大则如下: 
Select Name,sex,Count(*) From A Group By Name,sex Having Count(*) > 1 


(三) 
方法一 
declare @max integer,@id integer 
declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) >; 1 
open cur_rows 
fetch cur_rows into @id,@max 
while @@fetch_status=0 
begin 
select @max = @max -1 
set rowcount @max 
delete from 表名 where 主字段 = @id 
fetch cur_rows into @id,@max 
end 
close cur_rows 
set rowcount 0 


方法二 
"重复记录"有两个意义上的重复记录,一是完全重复的记录,也即所有字段均重复的记录,二是部分关键字段重复的记录,比如Name字段重复,而其他字段不一定重复或都重复可以忽略。 


  1、对于第一种重复,比较容易解决,使用 
select distinct * from tableName 
  就可以得到无重复记录的结果集。 
  如果该表需要删除重复的记录(重复记录保留1条),可以按以下方法删除 
select distinct * into #Tmp from tableName 
drop table tableName 
select * into tableName from #Tmp 
drop table #Tmp 
  发生这种重复的原因是表设计不周产生的,增加唯一索引列即可解决。 


  2、这类重复问题通常要求保留重复记录中的第一条记录,操作方法如下 
  假设有重复的字段为Name,Address,要求得到这两个字段唯一的结果集 
select identity(int,1,1) as autoID, * into #Tmp from tableName 
select min(autoID) as autoID into #Tmp2 from #Tmp group by Name,autoID 
select * from #Tmp where autoID in(select autoID from #tmp2) 
  最后一个select即得到了Name,Address不重复的结果集(但多了一个autoID字段,实际写时可以写在select子句中省去此列) 


(四) 
查询重复 
select * from tablename where id in ( 
select id from tablename 
group by id 
having count(id) > 1 
) 
三種download方式代碼 php
下載一個6.69G的avi文件,3種方式的下載效率性能測試。

<?php
$url = "http://192.168.2.3/test/david/AC4BFSP.avi";
$dest = date("Y-m-dHis") . ".avi";
//download_fread();
download_put_content();
//download_copy();
function download_copy()
{
	global $url;
	global $dest;
	echo date("Y-m-d H:i:s") . " start.<br/>";
	$result = copy($url, $dest); // 下载file gateway的zip
	if (!$result) {
		echo date("Y-m-d H:i:s") . " download file failed.<br/>";
	}
	echo date("Y-m-d H:i:s") . " end.<br/>";
}

function download_put_content()
{
	global $url;
	global $dest;
	echo date("Y-m-d H:i:s") . " start.<br/>";
	fopen($dest, 'wb+');
	$result = file_put_contents($dest, fopen($url, 'r'));
	if ($result === FALSE) {
		echo date("Y-m-d H:i:s") . " download file failed.<br/>";
	}
	echo date("Y-m-d H:i:s") . " end.<br/>";
}

function download_fread()
{
	set_time_limit(0);
	echo date("Y-m-d H:i:s") . " start.<br/>";
	global $url;
	global $dest;
	$fpWrite = @fopen($dest, "w+b");
	$fpRead  = @fopen($url, "rb");
	if (!$fpRead) {
		echo date("Y-m-d H:i:s") . " get source resource failed.<br/>";
		return;
	}
	if (!$fpWrite) {
		echo date("Y-m-d H:i:s") . " get dest resource failed.<br/>";
		return;
	}
	while (!feof($fpRead)) {
		fwrite($fpWrite, fread($fpRead, 512));
	}
	 
	fclose($fpWrite);
	fclose($fpRead);
	echo date("Y-m-d H:i:s") . " end.<br/>";
}
?>

file_put_content執行結果:
2014-07-31 10:58:07 start.
2014-07-31 11:01:23 download file failed.
2014-07-31 11:01:23 end.
用時3分23秒
即使下載成功,也返回false。

copy 執行結果:
2014-07-31 11:09:13 start.
2014-07-31 11:12:24 end.

用時 3分11秒

fread執行結果:
2014-07-31 11:14:36 start.
2014-07-31 11:18:51 end.

用時:4分15秒
將fwrite($fpWrite, fread($fpRead, 512));改成fwrite($fpWrite, fread($fpRead, 1024));

執行結果:
2014-07-31 11:29:11 start.
2014-07-31 11:32:26 end.

用時:3分15秒

從性能上分析,應該是fread會更好,不佔用太多內存。
requestAnimationFrame 兼容各个浏览器 html5
/*
 * Copyright (C) 2012 David Geary. This code is from the book
 * Core HTML5 Canvas, published by Prentice-Hall in 2012.
 *
 * License:
 *
 * Permission is hereby granted, free of charge, to any person 
 * obtaining a copy of this software and associated documentation files
 * (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * The Software may not be used to create training material of any sort,
 * including courses, books, instructional videos, presentations, etc.
 * without the express written consent of David Geary.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
*/

window.requestNextAnimationFrame =
   (function () {
      var originalWebkitRequestAnimationFrame = undefined,
          wrapper = undefined,
          callback = undefined,
          geckoVersion = 0,
          userAgent = navigator.userAgent,
          index = 0,
          self = this;

      // Workaround for Chrome 10 bug where Chrome
      // does not pass the time to the animation function
      
      if (window.webkitRequestAnimationFrame) {
         // Define the wrapper

         wrapper = function (time) {
           if (time === undefined) {
              time = +new Date();
           }
           self.callback(time);
         };

         // Make the switch
          
         originalWebkitRequestAnimationFrame = window.webkitRequestAnimationFrame;    

         window.webkitRequestAnimationFrame = function (callback, element) {
            self.callback = callback;

            // Browser calls the wrapper and wrapper calls the callback
            
            originalWebkitRequestAnimationFrame(wrapper, element);
         }
      }

      // Workaround for Gecko 2.0, which has a bug in
      // mozRequestAnimationFrame() that restricts animations
      // to 30-40 fps.

      if (window.mozRequestAnimationFrame) {
         // Check the Gecko version. Gecko is used by browsers
         // other than Firefox. Gecko 2.0 corresponds to
         // Firefox 4.0.
         
         index = userAgent.indexOf('rv:');

         if (userAgent.indexOf('Gecko') != -1) {
            geckoVersion = userAgent.substr(index + 3, 3);

            if (geckoVersion === '2.0') {
               // Forces the return statement to fall through
               // to the setTimeout() function.

               window.mozRequestAnimationFrame = undefined;
            }
         }
      }
      
      return window.requestAnimationFrame   ||
         window.webkitRequestAnimationFrame ||
         window.mozRequestAnimationFrame    ||
         window.oRequestAnimationFrame      ||
         window.msRequestAnimationFrame     ||

         function (callback, element) {
            var start,
                finish;

            window.setTimeout( function () {
               start = +new Date();
               callback(start);
               finish = +new Date();

               self.timeout = 1000 / 60 - (finish - start);

            }, self.timeout);
         };
      }
   )
();
requestAnimationFrame demo html5, javascript
<html>
	<script type="text/javascript">
		(function() {
		  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
									  window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
		  window.requestAnimationFrame = requestAnimationFrame;
		})();
		window.onload = function () {
			var start = window.mozAnimationStartTime;  // Only supported in FF. Other browsers can use something like Date.now().
	
			var div = document.getElementById("ele"),
				frame;
			function step(timestamp) {
			  var progress = timestamp - start;
			  div.style.left = Math.min(progress/10, 200) + "px";
			  requestAnimationFrame(step);
			}

			requestAnimationFrame(step);
		};
		
	</script>
	<body>
		<div id="ele" style="position:absolute;width:10px;height:10px;background:#ccc;"> </div>
	</body>
</html>
浏览器flash版本检测
导入 swfobject.js

 //flash版本检测  
 function checkFlashPlayer(){  
	 if(swfobject.ua.pv[0]){ //pv是一个版本号的对象
	     return true;  
	  }else{  
           return false;  
      }   
}  
jquery mobile 动态添加元素demo jquery mobile http://my.oschina.net/jgy/blog/101058
添加一个<input type='button' value='OK' id="btn_OK"/>然后调用jquery mobile 方法:$('#btn_OK').button();

jquery 表单元素每一个元素都有自己刷新的方法,每当改变它们的属性以后,都要执行这些方法,以下是实例:

复选按钮

$("input[type='checkbox']").attr("checked",true).checkboxradio("refresh");

 

单选按钮组:

$("input[type='radio']").attr("checked",true).checkboxradio("refresh");

 

选择列表::

var myselect = $("select#foo");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh"); 


 
滑动条

$("input[type=range]").val(60).slider("refresh");

 

开关 (they use slider):

var myswitch = $("select#bar");
myswitch[0].selectedIndex = 1;
myswitch .slider("refresh");



1.Textarea field


1
$('body').prepend('<textarea id="myTextArea"></textarea>');
2
$('#myTextArea').textinput();
2. Text input field

1
$('body').prepend('<input type="text" id="myTextField" />');
2
$('#myTextField').textinput();
3.button

1
$('body').prepend('<input type="text" id="myTextField" />');
2
$('#myTextField').textinput();
3. Combobox or select dropdowns

01
<label for="sCountry">Country:</label>
02
<select name="sCountry" id="sCountry">
03
    <option value="">Where You Live:</option>
04
    <option value="ad">Andorra</option>
05
    <option value="ae">United Arab Emirates</option>
06
</select>
07
  
08
var myselect = $("#sCountry");
09
myselect[0].selectedIndex = 3;
10
myselect.selectmenu('refresh');
4.最常见的动态添加 listview>li 标签
1
<ul id="myList" data-role="listview" data-inset="true">
2
    <li>A</li>
3
    <li>B</li>
4
    <li>C</li>
5
</ul>
6
  
7
$('#mylist').listview('refresh');
5.Slider control 


1
<div data-role="fieldcontain">
2
    <label for="slider-2">Input slider:</label>
3
    <input type="range" id="slider-2" value="25" min="0" max="100" />
4
</div>
5
  
6
$('#slider-2').val(80).slider('refresh');
6.Toggle switch

01
<span><div data-role="fieldcontain">
02
    <label for="toggle">Flip switch:</label>
03
    <select name="toggle" id="toggle" data-role="slider">
04
        <option value="off">Off</option>
05
        <option value="on">On</option>
06
    </select>
07
</div>
08
  
09
var myswitch = $("#toggle");
10
myswitch[0].selectedIndex = 1;
11
myswitch .slider("refresh");</span>

7. Radio

view sourceprint?
01
<span><div data-role="fieldcontain">
02
    <fieldset data-role="controlgroup" data-type="horizontal">
03
        <legend>Layout view:</legend>
04
            <input type="radio" name="radio-view" value="list"  />
05
            <label for="radio-view-a">List</label>
06
            <input type="radio" name="radio-view" value="grid"  />
07
            <label for="radio-view-b">Grid</label>
08
            <input type="radio" name="radio-view" value="gallery"  />
09
            <label for="radio-view-c">Gallery</label>
10
    </fieldset>
11
</div>
12
  
13
$("input[value=grid]").attr('checked',true).checkboxradio('refresh');</span>
8. Checkboxes 

1
<div data-role="fieldcontain">
2
    <fieldset data-role="controlgroup">
3
        <legend>Agree to the terms:</legend>
4
        <input type="checkbox" name="checkbox-1" id="checkbox-1" class="custom" />
5
        <label for="checkbox-1">I agree</label>
6
    </fieldset>
7
</div>
8
  
9
$('#checkbox-1').attr('checked',true).checkboxradio('refresh');
还有很多还需要慢慢发现!我做的是一个移动点餐系统:目前产品界面显示如下图:不知道有没有谁自己封装的listview,或者号的插件推荐我使用的!或有更好的建议……欢迎发表。。。。。 
sortable iscoller html5 iscroll
<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<title>iScroll 4</title>

		<style type="text/css" media="all">
			body, ul, li {
				padding: 0;
				margin: 0;
				border: 0;
			}

			body {
				font-size: 12px;
				-webkit-user-select: none;
				-webkit-text-size-adjust: none;
				font-family: helvetica;
			}

			#header {
				position: absolute;
				z-index: 2;
				top: 0;
				left: 0;
				width: 100%;
				height: 45px;
				line-height: 45px;
				background-color: #d51875;
				background-image: -webkit-gradient(linear, 0 0, 0 100%, color-stop(0, #fe96c9), color-stop(0.05, #d51875), color-stop(1, #7b0a2e));
				background-image: -moz-linear-gradient(top, #fe96c9, #d51875 5%, #7b0a2e);
				background-image: -o-linear-gradient(top, #fe96c9, #d51875 5%, #7b0a2e);
				padding: 0;
				color: #eee;
				font-size: 20px;
				text-align: center;
			}

			#header a {
				color: #f3f3f3;
				text-decoration: none;
				font-weight: bold;
				text-shadow: 0 -1px 0 rgba(0,0,0,0.5);
			}

			#footer {
				position: absolute;
				z-index: 2;
				bottom: 0;
				left: 0;
				width: 100%;
				height: 48px;
				background-color: #222;
				background-image: -webkit-gradient(linear, 0 0, 0 100%, color-stop(0, #999), color-stop(0.02, #666), color-stop(1, #222));
				background-image: -moz-linear-gradient(top, #999, #666 2%, #222);
				background-image: -o-linear-gradient(top, #999, #666 2%, #222);
				padding: 0;
				border-top: 1px solid #444;
			}

			#wrapper {
				position: absolute;
				z-index: 1;
				top: 45px;
				bottom: 48px;
				left: 0;
				width: 100%;
				background: #aaa;
				overflow: auto;
			}

			#scroller {
				position: absolute;
				z-index: 1;
				/*	-webkit-touch-callout:none;*/
				-webkit-tap-highlight-color: rgba(0,0,0,0);
				width: 100%;
				padding: 0;
			}

			#scroller ul {
				list-style: none;
				padding: 0;
				margin: 0;
				width: 100%;
				text-align: left;
			}

			#scroller li {
				padding: 0 10px;
				height: 40px;
				line-height: 40px;
				border-bottom: 1px solid #ccc;
				border-top: 1px solid #fff;
				background-color: #fafafa;
				font-size: 14px;
			}
		</style>
	</head>
	<body>

		<div id="header">
			iScroll 4
			<button id="butScroll">
				Done
			</button>
			<button id="butSort">
				Edit order
			</button>
		</div>
		<div id="wrapper">
			<div id="scroller">
				<ul id="itemsList">
					<li>
						<label> Pretty row 1 </label>
					</li>
					<li>
						<label> Pretty row 2 </label>
					</li>
					<li>
						<label> Pretty row 3 </label>
					</li>
					<li>
						<label> Pretty row 4 </label>
					</li>
					<li>
						<label> Pretty row 5 </label>
					</li>
					<li>
						<label> Pretty row 6 </label>
					</li>
					<li>
						<label> Pretty row 7 </label>
					</li>
					<li>
						<label> Pretty row 8 </label>
					</li>
					<li>
						<label> Pretty row 9 </label>
					</li>
					<li>
						<label> Pretty row 10 </label>
					</li>
					<li>
						<label> Pretty row 11 </label>
					</li>
					<li>
						<label> Pretty row 12 </label>
					</li>
					<li>
						<label> Pretty row 13 </label>
					</li>
					<li>
						<label> Pretty row 14 </label>
					</li>
					<li>
						<label> Pretty row 15 </label>
					</li>
					<li>
						<label> Pretty row 16 </label>
					</li>
					<li>
						<label> Pretty row 17 </label>
					</li>
					<li>
						<label> Pretty row 18 </label>
					</li>
					<li>
						<label> Pretty row 19 </label>
					</li>
					<li>
						<label> Pretty row 20 </label>
					</li>
					<li>
						<label> Pretty row 21 </label>
					</li>
					<li>
						<label> Pretty row 22 </label>
					</li>
					<li>
						<label> Pretty row 23 </label>
					</li>
					<li>
						<label> Pretty row 24 </label>
					</li>
					<li>
						<label> Pretty row 25 </label>
					</li>
					<li>
						<label> Pretty row 26 </label>
					</li>
					<li>
						<label> Pretty row 27 </label>
					</li>
					<li>
						<label> Pretty row 28 </label>
					</li>
					<li>
						<label> Pretty row 29 </label>
					</li>
					<li>
						<label> Pretty row 30 </label>
					</li>
					<li>
						<label> Pretty row 31 </label>
					</li>
					<li>
						<label> Pretty row 32 </label>
					</li>
					<li>
						<label> Pretty row 33 </label>
					</li>
					<li>
						<label> Pretty row 34 </label>
					</li>
					<li>
						<label> Pretty row 35 </label>
					</li>
					<li>
						<label> Pretty row 36 </label>
					</li>
					<li>
						<label> Pretty row 37 </label>
					</li>
					<li>
						<label> Pretty row 38 </label>
					</li>
					<li>
						<label> Pretty row 39 </label>
					</li>
					<li>
						<label> Pretty row 40 </label>
					</li>
				</ul>
			</div>
		</div>
		<div id="footer"></div>
		<script src="js/libs/jquery-1.7.2.min.js"></script>
		<script src="js/libs/jquery-ui-1.8.21.custom.min.js"></script>
		<script src="js/libs/jquery.ui.touch-punch.min.js"></script>
		<script type="application/javascript" src="js/libs/iscroll.js"></script>
		<script type="text/javascript">
			var myApp = myApp || {};

			myApp.enableSort = myApp.enableSort ||
			function enableSort() {
				$("#butSort").hide();
				$("#butScroll").show();
				
			// Record last pos from iScroll
				var currentY = myApp.myScroll.y;
			// If iScroll was not at the top then move it there
			// before we enable .sortable()
				if (currentY < 0) {
					myApp.myScroll.scrollTo(0, 0, 0, false);
				}
				
				myApp.myScroll.disable();
				
				$("#wrapper").css("overflow", "");
				$("#itemsList").sortable({
					handle : "label",
					axis : 'y',
					disabled : false
				});

				// If iScroll was not initally at the top, then move
				// it back down there (after having moved it to)
				// the top earlier.
				if (currentY < 0) {
					$("#wrapper").scrollTop(0 - currentY);
				}

			}

			myApp.enableiScroll = myApp.enableiScroll ||
			function() {
				// Record current pos from JS
				var currentY = $("#wrapper").scrollTop();
				$("#butSort").show();
				$("#butScroll").hide();
				$("#itemsList").sortable({
					disabled : true
				});
				myApp.myScroll = myApp.myScroll || new iScroll('wrapper');
				myApp.myScroll.enable();
				$("#wrapper").scrollTop(0 - currentY);
				// Scroll iScroll down to last recorded JS pos
				myApp.myScroll.scrollTo(0, 0 - currentY, 0, false);
				myApp.myScroll.refresh();
			}

			// jQuery's onload function
			$(function() {
				$("#butSort").click(function() {
					myApp.enableSort();
				});

				$("#butScroll").click(function() {
					myApp.enableiScroll();
				});
				
				myApp.enableiScroll();
			});

		</script>
	</body>
</html>
http://blog.csdn.net/jangle789/article/details/8460477 php做下载文件的实现代码及文件名中乱码, php
<?php 
header("Content-Type: application/force-download"); 
header("Content-Disposition: attachment; filename=ins.jpg"); 
readfile("imgs/test_Zoom.jpg"); 
?> 
第一行代码是强制下载; 
第二行代码是给下载的内容指定一个名字; 
第三行代码是把下载的内容读进文件中。 
如何在PHP下载文件名中解决乱码 
通过把Content-Type设置为application/octet-stream,可以把动态生成的内容当作文件来下载,相信这个大家都会。那么用Content-Disposition设置下载的文件名,这个也有不少人知道吧。基本上,下载程序都是这么写的:

<?php 
$filename = "document.txt"; 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename=' . $filename); 
print "Hello!"; 
?> 

这样用浏览器打开之后,就可以下载document.txt。 
但是,如果$filename是UTF-8编码的,有些浏览器就无法正常处理了。比如把上面那个程序稍稍改一下: 

<?php 
$filename = "中文 文件名.txt"; 
header('Content-Type: application/octet-stream'); 
header('Content-Disposition: attachment; filename=' . $filename); 
print "Hello!"; 
?> 

把程序保存成UTF-8编码再访问,IE6下载的文件名就会乱码。 FF3下下载的文件名就只有“中文”两个字。Opera 9下一切正常。 
输出的header实际上是这样子: 
Content-Disposition: attachment; filename=中文 文件名.txt其实按照RFC2231的定义,多语言编码的Content-Disposition应该这么定义:

Content-Disposition: attachment; filename*="utf8''%E4%B8%AD%E6%96%87%20%E6%96%87%E4%BB%B6%E5%90%8D.txt"

即: 
filename后面的等号之前要加 * 
filename的值用单引号分成三段,分别是字符集(utf8)、语言(空)和urlencode过的文件名。 
最好加上双引号,否则文件名中空格后面的部分在Firefox中显示不出来 
注意urlencode的结果与php的urlencode函数结果不太相同,php的urlencode会把空格替换成+,而这里需要替换成%20 
经过试验,发现几种主流浏览器的支持情况如下: 
IE6 attachment; filename="<URL编码之后的UTF-8文件名>" 
FF3 attachment; filename="UTF-8文件名" 
attachment; filename*="utf8''<URL编码之后的UTF-8文件名>" 
O9 attachment; filename="UTF-8文件名" 
Safari3(Win) 貌似不支持?上述方法都不行 
这样看来,程序必须得这样写才能支持所有主流浏览器: 

<?php 
$ua = $_SERVER["HTTP_USER_AGENT"]; 
$filename = "中文 文件名.txt"; 
$encoded_filename = urlencode($filename); 
$encoded_filename = str_replace("+", "%20", $encoded_filename); 
header('Content-Type: application/octet-stream'); 
if (preg_match("/MSIE/", $ua)) { 
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"'); 
} else if (preg_match("/Firefox/", $ua)) { 
header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
} else { 
header('Content-Disposition: attachment; filename="' . $filename . '"'); 
} 
print 'ABC'; 
?> 
 转自:http://www.alixixi.com/program/a/2011030368164.shtml
 
网上类似的文章有很多,这篇对我有用,收藏了
找这种方法,主要是自己要做PHPExcel操作保存文件,在文件名搜狗下正常显示空格,IE空格变成了 '_' ,firefox直接截取了空格前的作为文件名,
参照上面文章,稍微修改了下,以防以后用得到:
<?php
.............//phpexcel操作略
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$filename =“中    文.xlsx”;
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
header('Content-Type: application/vnd.ms-excel');
//header("Content-Disposition: attachment;filename=".$filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
} else {
header('Content-Disposition: attachment; filename="' . $filename . '"');
}

$objWriter->save('php://output');
?>
phpqrcode 增加生成jpg的功能 php, qrcode http://phpqrcode.sourceforge.net/
phpqrcode 增加了生成jpg的功能。原生代码只有png的对开公开接口。
用法:
QRcode::png($_REQUEST['data'], $filename, $errorCorrectionLevel, $matrixPointSize, 2);    
QRcode::jpg($_REQUEST['data'], $filename, $errorCorrectionLevel, $matrixPointSize, 2);    

<?php

/*
 * PHP QR Code encoder
 *
 * This file contains MERGED version of PHP QR Code library.
 * It was auto-generated from full version for your convenience.
 *
 * This merged version was configured to not requre any external files,
 * with disabled cache, error loging and weker but faster mask matching.
 * If you need tune it up please use non-merged version.
 *
 * For full version, documentation, examples of use please visit:
 *
 *    http://phpqrcode.sourceforge.net/
 *    https://sourceforge.net/projects/phpqrcode/
 *
 * PHP QR Code is distributed under LGPL 3
 * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */
 
 

/*
 * Version: 1.1.4
 * Build: 2010100721
 */



//---- qrconst.php -----------------------------





/*
 * PHP QR Code encoder
 *
 * Common constants
 *
 * Based on libqrencode C library distributed under LGPL 2.1
 * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
 *
 * PHP QR Code is distributed under LGPL 3
 * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */
 
	// Encoding modes
	 
	define('QR_MODE_NUL', -1);
	define('QR_MODE_NUM', 0);
	define('QR_MODE_AN', 1);
	define('QR_MODE_8', 2);
	define('QR_MODE_KANJI', 3);
	define('QR_MODE_STRUCTURE', 4);

	// Levels of error correction.

	define('QR_ECLEVEL_L', 0);
	define('QR_ECLEVEL_M', 1);
	define('QR_ECLEVEL_Q', 2);
	define('QR_ECLEVEL_H', 3);
	
	// Supported output formats
	
	define('QR_FORMAT_TEXT', 0);
	define('QR_FORMAT_PNG',  1);
	
	class qrstr {
		public static function set(&$srctab, $x, $y, $repl, $replLen = false) {
			$srctab[$y] = substr_replace($srctab[$y], ($replLen !== false)?substr($repl,0,$replLen):$repl, $x, ($replLen !== false)?$replLen:strlen($repl));
		}
	}	



//---- merged_config.php -----------------------------




/*
 * PHP QR Code encoder
 *
 * Config file, tuned-up for merged verion
 */
     
    define('QR_CACHEABLE', false);       // use cache - more disk reads but less CPU power, masks and format templates are stored there
    define('QR_CACHE_DIR', false);       // used when QR_CACHEABLE === true
    define('QR_LOG_DIR', false);         // default error logs dir   
    
    define('QR_FIND_BEST_MASK', true);                                                          // if true, estimates best mask (spec. default, but extremally slow; set to false to significant performance boost but (propably) worst quality code
    define('QR_FIND_FROM_RANDOM', 2);                                                       // if false, checks all masks available, otherwise value tells count of masks need to be checked, mask id are got randomly
    define('QR_DEFAULT_MASK', 2);                                                               // when QR_FIND_BEST_MASK === false
                                                  
    define('QR_PNG_MAXIMUM_SIZE',  1024);                                                       // maximum allowed png image width (in pixels), tune to make sure GD and PHP can handle such big images
                                                  



//---- qrtools.php -----------------------------




/*
 * PHP QR Code encoder
 *
 * Toolset, handy and debug utilites.
 *
 * PHP QR Code is distributed under LGPL 3
 * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

    class QRtools {
    
        //----------------------------------------------------------------------
        public static function binarize($frame)
        {
            $len = count($frame);
            foreach ($frame as &$frameLine) {
                
                for($i=0; $i<$len; $i++) {
                    $frameLine[$i] = (ord($frameLine[$i])&1)?'1':'0';
                }
            }
            
            return $frame;
        }
        
        //----------------------------------------------------------------------
        public static function tcpdfBarcodeArray($code, $mode = 'QR,L', $tcPdfVersion = '4.5.037')
        {
            $barcode_array = array();
            
            if (!is_array($mode))
                $mode = explode(',', $mode);
                
            $eccLevel = 'L';
                
            if (count($mode) > 1) {
                $eccLevel = $mode[1];
            }
                
            $qrTab = QRcode::text($code, false, $eccLevel);
            $size = count($qrTab);
                
            $barcode_array['num_rows'] = $size;
            $barcode_array['num_cols'] = $size;
            $barcode_array['bcode'] = array();
                
            foreach ($qrTab as $line) {
                $arrAdd = array();
                foreach(str_split($line) as $char)
                    $arrAdd[] = ($char=='1')?1:0;
                $barcode_array['bcode'][] = $arrAdd;
            }
                    
            return $barcode_array;
        }
        
        //----------------------------------------------------------------------
        public static function clearCache()
        {
            self::$frames = array();
        }
        
        //----------------------------------------------------------------------
        public static function buildCache()
        {
			QRtools::markTime('before_build_cache');
			
			$mask = new QRmask();
            for ($a=1; $a <= QRSPEC_VERSION_MAX; $a++) {
                $frame = QRspec::newFrame($a);
                if (QR_IMAGE) {
                    $fileName = QR_CACHE_DIR.'frame_'.$a.'.png';
                    QRimage::png(self::binarize($frame), $fileName, 1, 0);
                }
				
				$width = count($frame);
				$bitMask = array_fill(0, $width, array_fill(0, $width, 0));
				for ($maskNo=0; $maskNo<8; $maskNo++)
					$mask->makeMaskNo($maskNo, $width, $frame, $bitMask, true);
            }
			
			QRtools::markTime('after_build_cache');
        }

        //----------------------------------------------------------------------
        public static function log($outfile, $err)
        {
            if (QR_LOG_DIR !== false) {
                if ($err != '') {
                    if ($outfile !== false) {
                        file_put_contents(QR_LOG_DIR.basename($outfile).'-errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
                    } else {
                        file_put_contents(QR_LOG_DIR.'errors.txt', date('Y-m-d H:i:s').': '.$err, FILE_APPEND);
                    }
                }    
            }
        }
        
        //----------------------------------------------------------------------
        public static function dumpMask($frame) 
        {
            $width = count($frame);
            for($y=0;$y<$width;$y++) {
                for($x=0;$x<$width;$x++) {
                    echo ord($frame[$y][$x]).',';
                }
            }
        }
        
        //----------------------------------------------------------------------
        public static function markTime($markerId)
        {
            list($usec, $sec) = explode(" ", microtime());
            $time = ((float)$usec + (float)$sec);
            
            if (!isset($GLOBALS['qr_time_bench']))
                $GLOBALS['qr_time_bench'] = array();
            
            $GLOBALS['qr_time_bench'][$markerId] = $time;
        }
        
        //----------------------------------------------------------------------
        public static function timeBenchmark()
        {
            self::markTime('finish');
        
            $lastTime = 0;
            $startTime = 0;
            $p = 0;

            echo '<table cellpadding="3" cellspacing="1">
                    <thead><tr style="border-bottom:1px solid silver"><td colspan="2" style="text-align:center">BENCHMARK</td></tr></thead>
                    <tbody>';

            foreach($GLOBALS['qr_time_bench'] as $markerId=>$thisTime) {
                if ($p > 0) {
                    echo '<tr><th style="text-align:right">till '.$markerId.': </th><td>'.number_format($thisTime-$lastTime, 6).'s</td></tr>';
                } else {
                    $startTime = $thisTime;
                }
                
                $p++;
                $lastTime = $thisTime;
            }
            
            echo '</tbody><tfoot>
                <tr style="border-top:2px solid black"><th style="text-align:right">TOTAL: </th><td>'.number_format($lastTime-$startTime, 6).'s</td></tr>
            </tfoot>
            </table>';
        }
        
    }
    
    //##########################################################################
    
    QRtools::markTime('start');
    



//---- qrspec.php -----------------------------




/*
 * PHP QR Code encoder
 *
 * QR Code specifications
 *
 * Based on libqrencode C library distributed under LGPL 2.1
 * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
 *
 * PHP QR Code is distributed under LGPL 3
 * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
 *
 * The following data / specifications are taken from
 * "Two dimensional symbol -- QR-code -- Basic Specification" (JIS X0510:2004)
 *  or
 * "Automatic identification and data capture techniques -- 
 *  QR Code 2005 bar code symbology specification" (ISO/IEC 18004:2006)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */
 
    define('QRSPEC_VERSION_MAX', 40);
    define('QRSPEC_WIDTH_MAX',   177);

    define('QRCAP_WIDTH',        0);
    define('QRCAP_WORDS',        1);
    define('QRCAP_REMINDER',     2);
    define('QRCAP_EC',           3);

    class QRspec {
    
        public static $capacity = array(
            array(  0,    0, 0, array(   0,    0,    0,    0)),
            array( 21,   26, 0, array(   7,   10,   13,   17)), // 1
            array( 25,   44, 7, array(  10,   16,   22,   28)),
            array( 29,   70, 7, array(  15,   26,   36,   44)),
            array( 33,  100, 7, array(  20,   36,   52,   64)),
            array( 37,  134, 7, array(  26,   48,   72,   88)), // 5
            array( 41,  172, 7, array(  36,   64,   96,  112)),
            array( 45,  196, 0, array(  40,   72,  108,  130)),
            array( 49,  242, 0, array(  48,   88,  132,  156)),
            array( 53,  292, 0, array(  60,  110,  160,  192)),
            array( 57,  346, 0, array(  72,  130,  192,  224)), //10
            array( 61,  404, 0, array(  80,  150,  224,  264)),
            array( 65,  466, 0, array(  96,  176,  260,  308)),
            array( 69,  532, 0, array( 104,  198,  288,  352)),
            array( 73,  581, 3, array( 120,  216,  320,  384)),
            array( 77,  655, 3, array( 132,  240,  360,  432)), //15
            array( 81,  733, 3, array( 144,  280,  408,  480)),
            array( 85,  815, 3, array( 168,  308,  448,  532)),
            array( 89,  901, 3, array( 180,  338,  504,  588)),
            array( 93,  991, 3, array( 196,  364,  546,  650)),
            array( 97, 1085, 3, array( 224,  416,  600,  700)), //20
            array(101, 1156, 4, array( 224,  442,  644,  750)),
            array(105, 1258, 4, array( 252,  476,  690,  816)),
            array(109, 1364, 4, array( 270,  504,  750,  900)),
            array(113, 1474, 4, array( 300,  560,  810,  960)),
            array(117, 1588, 4, array( 312,  588,  870, 1050)), //25
            array(121, 1706, 4, array( 336,  644,  952, 1110)),
            array(125, 1828, 4, array( 360,  700, 1020, 1200)),
            array(129, 1921, 3, array( 390,  728, 1050, 1260)),
            array(133, 2051, 3, array( 420,  784, 1140, 1350)),
            array(137, 2185, 3, array( 450,  812, 1200, 1440)), //30
            array(141, 2323, 3, array( 480,  868, 1290, 1530)),
            array(145, 2465, 3, array( 510,  924, 1350, 1620)),
            array(149, 2611, 3, array( 540,  980, 1440, 1710)),
            array(153, 2761, 3, array( 570, 1036, 1530, 1800)),
            array(157, 2876, 0, array( 570, 1064, 1590, 1890)), //35
            array(161, 3034, 0, array( 600, 1120, 1680, 1980)),
            array(165, 3196, 0, array( 630, 1204, 1770, 2100)),
            array(169, 3362, 0, array( 660, 1260, 1860, 2220)),
            array(173, 3532, 0, array( 720, 1316, 1950, 2310)),
            array(177, 3706, 0, array( 750, 1372, 2040, 2430)) //40
        );
        
        //----------------------------------------------------------------------
        public static function getDataLength($version, $level)
        {
            return self::$capacity[$version][QRCAP_WORDS] - self::$capacity[$version][QRCAP_EC][$level];
        }
        
        //----------------------------------------------------------------------
        public static function getECCLength($version, $level)
        {
            return self::$capacity[$version][QRCAP_EC][$level];
        }
        
        //----------------------------------------------------------------------
        public static function getWidth($version)
        {
            return self::$capacity[$version][QRCAP_WIDTH];
        }
        
        //----------------------------------------------------------------------
        public static function getRemainder($version)
        {
            return self::$capacity[$version][QRCAP_REMINDER];
        }
        
        //----------------------------------------------------------------------
        public static function getMinimumVersion($size, $level)
        {

            for($i=1; $i<= QRSPEC_VERSION_MAX; $i++) {
                $words  = self::$capacity[$i][QRCAP_WORDS] - self::$capacity[$i][QRCAP_EC][$level];
                if($words >= $size) 
                    return $i;
            }

            return -1;
        }
    
        //######################################################################
        
        public static $lengthTableBits = array(
            array(10, 12, 14),
            array( 9, 11, 13),
            array( 8, 16, 16),
            array( 8, 10, 12)
        );
        
        //----------------------------------------------------------------------
        public static function lengthIndicator($mode, $version)
        {
            if ($mode == QR_MODE_STRUCTURE)
                return 0;
                
            if ($version <= 9) {
                $l = 0;
            } else if ($version <= 26) {
                $l = 1;
            } else {
                $l = 2;
            }

            return self::$lengthTableBits[$mode][$l];
        }
        
        //----------------------------------------------------------------------
        public static function maximumWords($mode, $version)
        {
            if($mode == QR_MODE_STRUCTURE) 
                return 3;
                
            if($version <= 9) {
                $l = 0;
            } else if($version <= 26) {
                $l = 1;
            } else {
                $l = 2;
            }

            $bits = self::$lengthTableBits[$mode][$l];
            $words = (1 << $bits) - 1;
            
            if($mode == QR_MODE_KANJI) {
                $words *= 2; // the number of bytes is required
            }

            return $words;
        }

        // Error correction code -----------------------------------------------
        // Table of the error correction code (Reed-Solomon block)
        // See Table 12-16 (pp.30-36), JIS X0510:2004.

        public static $eccTable = array(
            array(array( 0,  0), array( 0,  0), array( 0,  0), array( 0,  0)),
            array(array( 1,  0), array( 1,  0), array( 1,  0), array( 1,  0)), // 1
            array(array( 1,  0), array( 1,  0), array( 1,  0), array( 1,  0)),
            array(array( 1,  0), array( 1,  0), array( 2,  0), array( 2,  0)),
            array(array( 1,  0), array( 2,  0), array( 2,  0), array( 4,  0)),
            array(array( 1,  0), array( 2,  0), array( 2,  2), array( 2,  2)), // 5
            array(array( 2,  0), array( 4,  0), array( 4,  0), array( 4,  0)),
            array(array( 2,  0), array( 4,  0), array( 2,  4), array( 4,  1)),
            array(array( 2,  0), array( 2,  2), array( 4,  2), array( 4,  2)),
            array(array( 2,  0), array( 3,  2), array( 4,  4), array( 4,  4)),
            array(array( 2,  2), array( 4,  1), array( 6,  2), array( 6,  2)), //10
            array(array( 4,  0), array( 1,  4), array( 4,  4), array( 3,  8)),
            array(array( 2,  2), array( 6,  2), array( 4,  6), array( 7,  4)),
            array(array( 4,  0), array( 8,  1), array( 8,  4), array(12,  4)),
            array(array( 3,  1), array( 4,  5), array(11,  5), array(11,  5)),
            array(array( 5,  1), array( 5,  5), array( 5,  7), array(11,  7)), //15
            array(array( 5,  1), array( 7,  3), array(15,  2), array( 3, 13)),
            array(array( 1,  5), array(10,  1), array( 1, 15), array( 2, 17)),
            array(array( 5,  1), array( 9,  4), array(17,  1), array( 2, 19)),
            array(array( 3,  4), array( 3, 11), array(17,  4), array( 9, 16)),
            array(array( 3,  5), array( 3, 13), array(15,  5), array(15, 10)), //20
            array(array( 4,  4), array(17,  0), array(17,  6), array(19,  6)),
            array(array( 2,  7), array(17,  0), array( 7, 16), array(34,  0)),
            array(array( 4,  5), array( 4, 14), array(11, 14), array(16, 14)),
            array(array( 6,  4), array( 6, 14), array(11, 16), array(30,  2)),
            array(array( 8,  4), array( 8, 13), array( 7, 22), array(22, 13)), //25
            array(array(10,  2), array(19,  4), array(28,  6), array(33,  4)),
            array(array( 8,  4), array(22,  3), array( 8, 26), array(12, 28)),
            array(array( 3, 10), array( 3, 23), array( 4, 31), array(11, 31)),
            array(array( 7,  7), array(21,  7), array( 1, 37), array(19, 26)),
            array(array( 5, 10), array(19, 10), array(15, 25), array(23, 25)), //30
            array(array(13,  3), array( 2, 29), array(42,  1), array(23, 28)),
            array(array(17,  0), array(10, 23), array(10, 35), array(19, 35)),
            array(array(17,  1), array(14, 21), array(29, 19), array(11, 46)),
            array(array(13,  6), array(14, 23), array(44,  7), array(59,  1)),
            array(array(12,  7), array(12, 26), array(39, 14), array(22, 41)), //35
            array(array( 6, 14), array( 6, 34), array(46, 10), array( 2, 64)),
            array(array(17,  4), array(29, 14), array(49, 10), array(24, 46)),
            array(array( 4, 18), array(13, 32), array(48, 14), array(42, 32)),
            array(array(20,  4), array(40,  7), array(43, 22), array(10, 67)),
            array(array(19,  6), array(18, 31), array(34, 34), array(20, 61)),//40
        );                                                                       

        //----------------------------------------------------------------------
        // CACHEABLE!!!
        
        public static function getEccSpec($version, $level, array &$spec)
        {
            if (count($spec) < 5) {
                $spec = array(0,0,0,0,0);
            }

            $b1   = self::$eccTable[$version][$level][0];
            $b2   = self::$eccTable[$version][$level][1];
            $data = self::getDataLength($version, $level);
            $ecc  = self::getECCLength($version, $level);

            if($b2 == 0) {
                $spec[0] = $b1;
                $spec[1] = (int)($data / $b1);
                $spec[2] = (int)($ecc / $b1);
                $spec[3] = 0; 
                $spec[4] = 0;
            } else {
                $spec[0] = $b1;
                $spec[1] = (int)($data / ($b1 + $b2));
                $spec[2] = (int)($ecc  / ($b1 + $b2));
                $spec[3] = $b2;
                $spec[4] = $spec[1] + 1;
            }
        }

        // Alignment pattern ---------------------------------------------------

        // Positions of alignment patterns.
        // This array includes only the second and the third position of the 
        // alignment patterns. Rest of them can be calculated from the distance 
        // between them.
         
        // See Table 1 in Appendix E (pp.71) of JIS X0510:2004.
         
        public static $alignmentPattern = array(      
            array( 0,  0),
            array( 0,  0), array(18,  0), array(22,  0), array(26,  0), array(30,  0), // 1- 5
            array(34,  0), array(22, 38), array(24, 42), array(26, 46), array(28, 50), // 6-10
            array(30, 54), array(32, 58), array(34, 62), array(26, 46), array(26, 48), //11-15
            array(26, 50), array(30, 54), array(30, 56), array(30, 58), array(34, 62), //16-20
            array(28, 50), array(26, 50), array(30, 54), array(28, 54), array(32, 58), //21-25
            array(30, 58), array(34, 62), array(26, 50), array(30, 54), array(26, 52), //26-30
            array(30, 56), array(34, 60), array(30, 58), array(34, 62), array(30, 54), //31-35
            array(24, 50), array(28, 54), array(32, 58), array(26, 54), array(30, 58), //35-40
        );                                                                                  

        
        /** --------------------------------------------------------------------
         * Put an alignment marker.
         * @param frame
         * @param width
         * @param ox,oy center coordinate of the pattern
         */
        public static function putAlignmentMarker(array &$frame, $ox, $oy)
        {
            $finder = array(
                "\xa1\xa1\xa1\xa1\xa1",
                "\xa1\xa0\xa0\xa0\xa1",
                "\xa1\xa0\xa1\xa0\xa1",
                "\xa1\xa0\xa0\xa0\xa1",
                "\xa1\xa1\xa1\xa1\xa1"
            );                        
            
            $yStart = $oy-2;         
            $xStart = $ox-2;
            
            for($y=0; $y<5; $y++) {
                QRstr::set($frame, $xStart, $yStart+$y, $finder[$y]);
            }
        }

        //----------------------------------------------------------------------
        public static function putAlignmentPattern($version, &$frame, $width)
        {
            if($version < 2)
                return;

            $d = self::$alignmentPattern[$version][1] - self::$alignmentPattern[$version][0];
            if($d < 0) {
                $w = 2;
            } else {
                $w = (int)(($width - self::$alignmentPattern[$version][0]) / $d + 2);
            }

            if($w * $w - 3 == 1) {
                $x = self::$alignmentPattern[$version][0];
                $y = self::$alignmentPattern[$version][0];
                self::putAlignmentMarker($frame, $x, $y);
                return;
            }

            $cx = self::$alignmentPattern[$version][0];
            for($x=1; $x<$w - 1; $x++) {
                self::putAlignmentMarker($frame, 6, $cx);
                self::putAlignmentMarker($frame, $cx,  6);
                $cx += $d;
            }

            $cy = self::$alignmentPattern[$version][0];
            for($y=0; $y<$w-1; $y++) {
                $cx = self::$alignmentPattern[$version][0];
                for($x=0; $x<$w-1; $x++) {
                    self::putAlignmentMarker($frame, $cx, $cy);
                    $cx += $d;
                }
                $cy += $d;
            }
        }

        // Version information pattern -----------------------------------------

		// Version information pattern (BCH coded).
        // See Table 1 in Appendix D (pp.68) of JIS X0510:2004.
        
		// size: [QRSPEC_VERSION_MAX - 6]
		
        public static $versionPattern = array(
            0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d,
            0x0f928, 0x10b78, 0x1145d, 0x12a17, 0x13532, 0x149a6, 0x15683, 0x168c9,
            0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75,
            0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64,
            0x27541, 0x28c69
        );

        //----------------------------------------------------------------------
        public static function getVersionPattern($version)
        {
            if($version < 7 || $version > QRSPEC_VERSION_MAX)
                return 0;

            return self::$versionPattern[$version -7];
        }

        // Format information --------------------------------------------------
        // See calcFormatInfo in tests/test_qrspec.c (orginal qrencode c lib)
        
        public static $formatInfo = array(
            array(0x77c4, 0x72f3, 0x7daa, 0x789d, 0x662f, 0x6318, 0x6c41, 0x6976),
            array(0x5412, 0x5125, 0x5e7c, 0x5b4b, 0x45f9, 0x40ce, 0x4f97, 0x4aa0),
            array(0x355f, 0x3068, 0x3f31, 0x3a06, 0x24b4, 0x2183, 0x2eda, 0x2bed),
            array(0x1689, 0x13be, 0x1ce7, 0x19d0, 0x0762, 0x0255, 0x0d0c, 0x083b)
        );

        public static function getFormatInfo($mask, $level)
        {
            if($mask < 0 || $mask > 7)
                return 0;
                
            if($level < 0 || $level > 3)
                return 0;                

            return self::$formatInfo[$level][$mask];
        }

        // Frame ---------------------------------------------------------------
        // Cache of initial frames.
         
        public static $frames = array();

        /** --------------------------------------------------------------------
         * Put a finder pattern.
         * @param frame
         * @param width
         * @param ox,oy upper-left coordinate of the pattern
         */
        public static function putFinderPattern(&$frame, $ox, $oy)
        {
            $finder = array(
                "\xc1\xc1\xc1\xc1\xc1\xc1\xc1",
                "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
                "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
                "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
                "\xc1\xc0\xc1\xc1\xc1\xc0\xc1",
                "\xc1\xc0\xc0\xc0\xc0\xc0\xc1",
                "\xc1\xc1\xc1\xc1\xc1\xc1\xc1"
            );                            
            
            for($y=0; $y<7; $y++) {
                QRstr::set($frame, $ox, $oy+$y, $finder[$y]);
            }
        }

        //----------------------------------------------------------------------
        public static function createFrame($version)
        {
            $width = self::$capacity[$version][QRCAP_WIDTH];
            $frameLine = str_repeat ("\0", $width);
            $frame = array_fill(0, $width, $frameLine);

            // Finder pattern
            self::putFinderPattern($frame, 0, 0);
            self::putFinderPattern($frame, $width - 7, 0);
            self::putFinderPattern($frame, 0, $width - 7);
            
            // Separator
            $yOffset = $width - 7;
            
            for($y=0; $y<7; $y++) {
                $frame[$y][7] = "\xc0";
                $frame[$y][$width - 8] = "\xc0";
                $frame[$yOffset][7] = "\xc0";
                $yOffset++;
            }
            
            $setPattern = str_repeat("\xc0", 8);
            
            QRstr::set($frame, 0, 7, $setPattern);
            QRstr::set($frame, $width-8, 7, $setPattern);
            QRstr::set($frame, 0, $width - 8, $setPattern);
        
            // Format info
            $setPattern = str_repeat("\x84", 9);
            QRstr::set($frame, 0, 8, $setPattern);
            QRstr::set($frame, $width - 8, 8, $setPattern, 8);
            
            $yOffset = $width - 8;

            for($y=0; $y<8; $y++,$yOffset++) {
                $frame[$y][8] = "\x84";
                $frame[$yOffset][8] = "\x84";
            }

            // Timing pattern  
            
            for($i=1; $i<$width-15; $i++) {
                $frame[6][7+$i] = chr(0x90 | ($i & 1));
                $frame[7+$i][6] = chr(0x90 | ($i & 1));
            }
            
            // Alignment pattern  
            self::putAlignmentPattern($version, $frame, $width);
            
            // Version information 
            if($version >= 7) {
                $vinf = self::getVersionPattern($version);

                $v = $vinf;
                
                for($x=0; $x<6; $x++) {
                    for($y=0; $y<3; $y++) {
                        $frame[($width - 11)+$y][$x] = chr(0x88 | ($v & 1));
                        $v = $v >> 1;
                    }
                }

                $v = $vinf;
                for($y=0; $y<6; $y++) {
                    for($x=0; $x<3; $x++) {
                        $frame[$y][$x+($width - 11)] = chr(0x88 | ($v & 1));
                        $v = $v >> 1;
                    }
                }
            }
    
            // and a little bit...  
            $frame[$width - 8][8] = "\x81";
            
            return $frame;
        }

        //----------------------------------------------------------------------
        public static function debug($frame, $binary_mode = false)
        {
            if ($binary_mode) {
            
                    foreach ($frame as &$frameLine) {
                        $frameLine = join('<span class="m">  </span>', explode('0', $frameLine));
                        $frameLine = join('██', explode('1', $frameLine));
                    }
                    
                    ?>
                <style>
                    .m { background-color: white; }
                </style>
                <?php
                    echo '<pre><tt><br/ ><br/ ><br/ >        ';
                    echo join("<br/ >        ", $frame);
                    echo '</tt></pre><br/ ><br/ ><br/ ><br/ ><br/ ><br/ >';
            
            } else {
            
                foreach ($frame as &$frameLine) {
                    $frameLine = join('<span class="m"> </span>',  explode("\xc0", $frameLine));
                    $frameLine = join('<span class="m">▒</span>', explode("\xc1", $frameLine));
                    $frameLine = join('<span class="p"> </span>',  explode("\xa0", $frameLine));
                    $frameLine = join('<span class="p">▒</span>', explode("\xa1", $frameLine));
                    $frameLine = join('<span class="s">◇</span>', explode("\x84", $frameLine)); //format 0
                    $frameLine = join('<span class="s">◆</span>', explode("\x85", $frameLine)); //format 1
                    $frameLine = join('<span class="x">☢</span>', explode("\x81", $frameLine)); //special bit
                    $frameLine = join('<span class="c"> </span>',  explode("\x90", $frameLine)); //clock 0
                    $frameLine = join('<span class="c">◷</span>', explode("\x91", $frameLine)); //clock 1
                    $frameLine = join('<span class="f"> </span>',  explode("\x88", $frameLine)); //version
                    $frameLine = join('<span class="f">▒</span>', explode("\x89", $frameLine)); //version
                    $frameLine = join('♦', explode("\x01", $frameLine));
                    $frameLine = join('⋅', explode("\0", $frameLine));
                }
                
                ?>
                <style>
                    .p { background-color: yellow; }
                    .m { background-color: #00FF00; }
                    .s { background-color: #FF0000; }
                    .c { background-color: aqua; }
                    .x { background-color: pink; }
                    .f { background-color: gold; }
                </style>
                <?php
                echo "<pre><tt>";
                echo join("<br/ >", $frame);
                echo "</tt></pre>";
            
            }
        }

        //----------------------------------------------------------------------
        public static function serial($frame)
        {
            return gzcompress(join("\n", $frame), 9);
        }
        
        //----------------------------------------------------------------------
        public static function unserial($code)
        {
            return explode("\n", gzuncompress($code));
        }
        
        //----------------------------------------------------------------------
        public static function newFrame($version)
        {
            if($version < 1 || $version > QRSPEC_VERSION_MAX) 
                return null;

            if(!isset(self::$frames[$version])) {
                
                $fileName = QR_CACHE_DIR.'frame_'.$version.'.dat';
                
                if (QR_CACHEABLE) {
                    if (file_exists($fileName)) {
                        self::$frames[$version] = self::unserial(file_get_contents($fileName));
                    } else {
                        self::$frames[$version] = self::createFrame($version);
                        file_put_contents($fileName, self::serial(self::$frames[$version]));
                    }
                } else {
                    self::$frames[$version] = self::createFrame($version);
                }
            }
            
            if(is_null(self::$frames[$version]))
                return null;

            return self::$frames[$version];
        }

        //----------------------------------------------------------------------
        public static function rsBlockNum($spec)     { return $spec[0] + $spec[3]; }
        public static function rsBlockNum1($spec)    { return $spec[0]; }
        public static function rsDataCodes1($spec)   { return $spec[1]; }
        public static function rsEccCodes1($spec)    { return $spec[2]; }
        public static function rsBlockNum2($spec)    { return $spec[3]; }
        public static function rsDataCodes2($spec)   { return $spec[4]; }
        public static function rsEccCodes2($spec)    { return $spec[2]; }
        public static function rsDataLength($spec)   { return ($spec[0] * $spec[1]) + ($spec[3] * $spec[4]);    }
        public static function rsEccLength($spec)    { return ($spec[0] + $spec[3]) * $spec[2]; }
        
    }



//---- qrimage.php -----------------------------




/*
 * PHP QR Code encoder
 *
 * Image output of code using GD2
 *
 * PHP QR Code is distributed under LGPL 3
 * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */
 
    define('QR_IMAGE', true);

    class QRimage {
    
        //----------------------------------------------------------------------
        public static function png($frame, $filename = false, $pixelPerPoint = 4, $outerFrame = 4,$saveandprint=FALSE) 
        {
            $image = self::image($frame, $pixelPerPoint, $outerFrame);
            
            if ($filename === false) {
                Header("Content-type: image/png");
                ImagePng($image);
            } else {
                if($saveandprint===TRUE){
                    ImagePng($image, $filename);
                    header("Content-type: image/png");
                    ImagePng($image);
                }else{
                    ImagePng($image, $filename);
                }
            }
            
            ImageDestroy($image);
        }
    
        //----------------------------------------------------------------------
        public static function jpg($frame, $filename = false, $pixelPerPoint = 8, $outerFrame = 4, $q = 85) 
        {
            $image = self::image($frame, $pixelPerPoint, $outerFrame);
            
            if ($filename === false) {
                Header("Content-type: image/jpeg");
                ImageJpeg($image, null, $q);
            } else {
                ImageJpeg($image, $filename, $q);            
            }
            
            ImageDestroy($image);
        }
    
        //----------------------------------------------------------------------
        private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4) 
        {
            $h = count($frame);
            $w = strlen($frame[0]);
            
            $imgW = $w + 2*$outerFrame;
            $imgH = $h + 2*$outerFrame;
            
            $base_image =ImageCreate($imgW, $imgH);
            
            $col[0] = ImageColorAllocate($base_image,255,255,255);
            $col[1] = ImageColorAllocate($base_image,0,0,0);

            imagefill($base_image, 0, 0, $col[0]);

            for($y=0; $y<$h; $y++) {
                for($x=0; $x<$w; $x++) {
                    if ($frame[$y][$x] == '1') {
                        ImageSetPixel($base_image,$x+$outerFrame,$y+$outerFrame,$col[1]); 
                    }
                }
            }
            
            $target_image =ImageCreate($imgW * $pixelPerPoint, $imgH * $pixelPerPoint);
            ImageCopyResized($target_image, $base_image, 0, 0, 0, 0, $imgW * $pixelPerPoint, $imgH * $pixelPerPoint, $imgW, $imgH);
            ImageDestroy($base_image);
            
            return $target_image;
        }
    }



//---- qrinput.php -----------------------------




/*
 * PHP QR Code encoder
 *
 * Input encoding class
 *
 * Based on libqrencode C library distributed under LGPL 2.1
 * Copyright (C) 2006, 2007, 2008, 2009 Kentaro Fukuchi <fukuchi@megaui.net>
 *
 * PHP QR Code is distributed under LGPL 3
 * Copyright (C) 2010 Dominik Dzienia <deltalab at poczta dot fm>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */
 
    define('STRUCTURE_HEADER_BITS',  20);
    define('MAX_STRUCTURED_SYMBOLS', 16);

    class QRinputItem {
    
        public $mode;
        public $size;
        public $data;
        public $bstream;

        public function __construct($mode, $size, $data, $bstream = null) 
        {
            $setData = array_slice($data, 0, $size);
            
            if (count($setData) < $size) {
                $setData = array_merge($setData, array_fill(0,$size-count($setData),0));
            }
        
            if(!QRinput::check($mode, $size, $setData)) {
                throw new Exception('Error m:'.$mode.',s:'.$size.',d:'.join(',',$setData));
                return null;
            }
            
            $this->mode = $mode;
            $this->size = $size;
            $this->data = $setData;
            $this->bstream = $bstream;
        }
        
        //----------------------------------------------------------------------
        public function encodeModeNum($version)
        {
            try {
            
                $words = (int)($this->size / 3);
                $bs = new QRbitstream();
                
                $val = 0x1;
                $bs->appendNum(4, $val);
                $bs->appendNum(QRspec::lengthIndicator(QR_MODE_NUM, $version), $this->size);

                for($i=0; $i<$words; $i++) {
                    $val  = (ord($this->data[$i*3  ]) - ord('0')) * 100;
                    $val += (ord($this->data[$i*3+1]) - ord('0')) * 10;
                    $val += (ord($this->data[$i*3+2]) - ord('0'));
                    $bs->appendNum(10, $val);
                }

                if($this->size - $words * 3 == 1) {
                    $val = ord($this->data[$words*3]) - ord('0');
                    $bs->appendNum(4, $val);
                } else if($this->size - $words * 3 == 2) {
                    $val  = (ord($this->data[$words*3  ]) - ord('0')) * 10;
                    $val += (ord($this->data[$words*3+1]) - ord('0'));
                    $bs->appendNum(7, $val);
                }

                $this->bstream = $bs;
                return 0;
                
            } catch (Exception $e) {
                return -1;
            }
        }
        
        //----------------------------------------------------------------------
        public function encodeModeAn($version)
        {
            try {
                $words = (int)($this->size / 2);
                $bs = new QRbitstream();
                
                $bs->appendNum(4, 0x02);
                $bs->appendNum(QRspec::lengthIndicator(QR_MODE_AN, $version), $this->size);

                for($i=0; $i<$words; $i++) {
                    $val  = (int)QRinput::lookAnTable(ord($this->data[$i*2  ])) * 45;
                    $val += (int)QRinput::lookAnTable(ord($this->data[$i*2+1]));

                    $bs->appendNum(11, $val);
                }

                if($this->size & 1) {
                    $val = QRinput::lookAnTable(ord($this->data[$words * 2]));
                    $bs->appendNum(6, $val);
                }
        
                $this->bstream = $bs;
                return 0;
            
            } catch (Exception $e) {
                return -1;
            }
        }
        
        //----------------------------------------------------------------------
        public function encodeMode8($version)
        {
            try {
                $bs = new QRbitstream();

                $bs->appendNum(4, 0x4);
                $bs->appendNum(QRspec::lengthIndicator(QR_MODE_8, $version), $this->size);

                for($i=0; $i<$this->size; $i++) {
                    $bs->appendNum(8, ord($this->data[$i]));
                }

                $this->bstream = $bs;
                return 0;
            
            } catch (Exception $e) {
                return -1;
            }
        }
        
        //----------------------------------------------------------------------
        public function encodeModeKanji($version)
        {
            try {

                $bs = new QRbitrtream();
                
                $bs->appendNum(4, 0x8);
                $bs->appendNum(QRspec::lengthIndicator(QR_MODE_KANJI, $version), (int)($this->size / 2));

                for($i=0; $i<$this->size; $i+=2) {
                    $val = (ord($this->data[$i]) << 8) | ord($this->data[$i+1]);
                    if($val <= 0x9ffc) {
                        $val -= 0x8140;
                    } else {
                        $val -= 0xc140;
                    }
                    
                    $h = ($val >> 8) * 0xc0;
                    $val = ($val & 0xff) + $h;

                    $bs->appendNum(13, $val);
                }

                $this->bstream = $bs;
                return 0;
            
            } catch (Exception $e) {
                return -1;
            }
        }

        //----------------------------------------------------------------------
        public function encodeModeStructure()
        {
            try {
                $bs =  new QRbitstream();
                
                $bs->appendNum(4, 0x03);
                $bs->appendNum(4, ord($this->data[1]) - 1);
                $bs->appendNum(4, ord($this->data[0]) - 1);
                $bs->appendNum(8, ord($this->data[2]));

                $this->bstream = $bs;
                return 0;
            
            } catch (Exception $e) {
                return -1;
            }
        }
        
        //----------------------------------------------------------------------
        public function estimateBitStreamSizeOfEntry($version)
        {
            $bits = 0;

            if($version == 0) 
                $version = 1;

            switch($this->mode) {
                case QR_MODE_NUM:        $bits = QRinput::estimateBitsModeNum($this->size);    break;
                case QR_MODE_AN:        $bits = QRinput::estimateBitsModeAn($this->size);    break;
                case QR_MODE_8:            $bits = QRinput::estimateBitsMode8($this->size);    break;
                case QR_MODE_KANJI:        $bits = QRinput::estimateBitsModeKanji($this->size);break;
                case QR_MODE_STRUCTURE:    return STRUCTURE_HEADER_BITS;            
                default:
                    return 0;
            }

            $l = QRspec::lengthIndicator($this->mode, $version);
            $m = 1 << $l;
            $num = (int)(($this->size + $m - 1) / $m);

            $bits += $num * (4 + $l);

            return $bits;
        }
        
        //----------------------------------------------------------------------
        public function encodeBitStream($version)
        {
            try {
            
                unset($this->bstream);
                $words = QRspec::maximumWords($this->mode, $version);
                
                if($this->size > $words) {
                
                    $st1 = new QRinputItem($this->mode, $words, $this->data);
                    $st2 = new QRinputItem($this->mode, $this->size - $words, array_slice($this->data, $words));

                    $st1->encodeBitStream($version);
                    $st2->encodeBitStream($version);
                    
                    $this->bstream = new QRbitstream();
                    $this->bstream->append($st1->bstream);
                    $this->bstream->append($st2->bstream);
                    
                    unset($st1);
                    unset($st2);
                    
                } else {
                    
                    $ret = 0;
                    
                    switch($this->mode) {
                        case QR_MODE_NUM:        $ret = $this->encodeModeNum($version);    break;
                        case QR_MODE_AN:        $ret = $this->encodeModeAn($version);    break;
                        case QR_MODE_8:            $ret = $this->encodeMode8($version);    break;
                        case QR_MODE_KANJI:        $ret = $this->encodeModeKanji($version);break;
                        case QR_MODE_STRUCTURE:    $ret = $this->encodeModeStructure();    break;
                        
                        default:
                            break;
                    }
                    
                    if($ret < 0)
                        return -1;
                }

                return $this->bstream->size();
            
            } catch (Exception $e) {
                return -1;
            }
        }
    };
    
    //##########################################################################

    class QRinput {

        public $items;
        
        private $version;
        private $level;
        
        //----------------------------------------------------------------------
        public function __construct($version = 0, $level = QR_ECLEVEL_L)
        {
            if ($version < 0 || $version > QRSPEC_VERSION_MAX || $level > QR_ECLEVEL_H) {
                throw new Exception('Invalid version no');
                return NULL;
            }
            
            $this->version = $version;
            $this->level = $level;
        }
        
        //----------------------------------------------------------------------
        public function getVersion()
        {
            return $this->version;
        }
        
        //----------------------------------------------------------------------
        public function setVersion($version)
        {
            if($version < 0 || $version > QRSPEC_VERSION_MAX) {
                throw new Exception('Invalid version no');
                return -1;
            }

            $this->version = $version;

            return 0;
        }
        
        //----------------------------------------------------------------------
        public function getErrorCorrectionLevel()
        {
            return $this->level;
        }

        //----------------------------------------------------------------------
        public function setErrorCorrectionLevel($level)
        {
            if($level > QR_ECLEVEL_H) {
                throw new Exception('Invalid ECLEVEL');
                return -1;
            }

            $this->level = $level;

            return 0;
        }
        
        //----------------------------------------------------------------------
        public function appendEntry(QRinputItem $entry)
        {
            $this->items[] = $entry;
        }
        
        //----------------------------------------------------------------------
        public function append($mode, $size, $data)
        {
            try {
                $entry = new QRinputItem($mode, $size, $data);
                $this->items[] = $entry;
                return 0;
            } catch (Exception $e) {
                return -1;
            }
        }
        
        //----------------------------------------------------------------------
        
        public function insertStructuredAppendHeader($size, $index, $parity)
        {
            if( $size > MAX_STRUCTURED_SYMBOLS ) {
                throw new Exception('insertStructuredAppendHeader wrong size');
            }
            
            if( $index <= 0 || $index > MAX_STRUCTURED_SYMBOLS ) {
                throw new Exception('insertStructuredAppendHeader wrong index');
            }

            $buf = array($size, $index, $parity);
            
            try {
                $entry = new QRinputItem(QR_MODE_STRUCTURE, 3, buf);
                array_unshift($this->items, $entry);
                return 0;
            } catch (Exception $e) {
                return -1;
            }
        }

        //----------------------------------------------------------------------
        public function calcParity()
        {
            $parity = 0;
            
            foreach($this->items as $item) {
                if($item->mode != QR_MODE_STRUCTURE) {
                    for($i=$item->size-1; $i>=0; $i--) {
                        $parity ^= $item->data[$i];
                    }
                }
            }

            return $parity;
        }
        
        //----------------------------------------------------------------------
        public static function checkModeNum($size, $data)
        {
            for($i=0; $i<$size; $i++) {
                if((ord($data[$i]) < ord('0')) || (ord($data[$i]) > ord('9'))){
                    return false;
                }
            }

            return true;
        }

        //----------------------------------------------------------------------
        public static function estimateBitsModeNum($size)
        {
            $w = (int)$size / 3;
            $bits = $w * 10;
            
            switch($size - $w * 3) {
                case 1:
                    $bits += 4;
                    break;
                case 2:
                    $bits += 7;
                    break;
                default:
                    break;
            }

            return $bits;
        }
        
        //----------------------------------------------------------------------
        public static $anTable = array(
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43,
             0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 44, -1, -1, -1, -1, -1,
            -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
            25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
            -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
        );
        
        //----------------------------------------------------------------------
        public static function lookAnTable($c)
        {
            return (($c > 127)?-1:self::$anTable[$c]);
        }
        
        //----------------------------------------------------------------------
        public static function checkModeAn($size, $data)
        {
            for($i=0; $i<$size; $i++) {
                if (self::lookAnTable(ord($data[$i])) == -1) {
                    return false;
                }
            }

            return true;
        }
        
        //----------------------------------------------------------------------
        public static function estimateBitsModeAn($size)
        {
            $w = (int)($size / 2);
            $bits = $w * 11;
            
            if($size & 1) {
                $bits += 6;
            }

            return $bits;
        }
    
        //----------------------------------------------------------------------
        public static function estimateBitsMode8($size)
        {
            return $size * 8;
        }
        
        //----------------------------------------------------------------------
        public function estimateBitsModeKanji($size)
        {
            return (int)(($size / 2) * 13);
        }
        
        //----------------------------------------------------------------------
        public static function checkModeKanji($size, $data)
        {
            if($size & 1)
                return false;

            for($i=0; $i<$size; $i+=2) {
                $val = (ord($data[$i]) << 8) | ord($data[$i+1]);
                if( $val < 0x8140 
                || ($val > 0x9ffc && $val < 0xe040) 
                || $val > 0xebbf) {
                    return false;
                }
            }

            return true;
        }

        /***********************************************************************
         * Validation
         **********************************************************************/

        public static function check($mode, $size, $data)
        {
            if($size <= 0) 
                return false;

            switch($mode) {
                case QR_MODE_NUM:       return self::checkModeNum($size, $data);   break;
                case QR_MODE_AN:        return self::checkModeAn($size, $data);    break;
                case QR_MODE_KANJI:     return self::checkModeKanji($size, $data); break;
                case QR_MODE_8:         return true; break;
                case QR_MODE_STRUCTURE: return true; break;
                
                default:
                    break;
            }

            return false;
        }
        
        
        //----------------------------------------------------------------------
        public function estimateBitStreamSize($version)
        {
            $bits = 0;

            foreach($this->items as $item) {
                $bits += $item->estimateBitStreamSizeOfEntry($version);
            }

            return $bits;
        }
        
        //----------------------------------------------------------------------
        public function estimateVersion()
        {
            $version = 0;
            $prev = 0;
            do {
                $prev = $version;
                $bits = $this->estimateBitStreamSize($prev);
                $version = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
                if ($version < 0) {
                    return -1;
                }
            } while ($version > $prev);

            return $version;
        }
        
        //----------------------------------------------------------------------
        public static function lengthOfCode($mode, $version, $bits)
        {
            $payload = $bits - 4 - QRspec::lengthIndicator($mode, $version);
            switch($mode) {
                case QR_MODE_NUM:
                    $chunks = (int)($payload / 10);
                    $remain = $payload - $chunks * 10;
                    $size = $chunks * 3;
                    if($remain >= 7) {
                        $size += 2;
                    } else if($remain >= 4) {
                        $size += 1;
                    }
                    break;
                case QR_MODE_AN:
                    $chunks = (int)($payload / 11);
                    $remain = $payload - $chunks * 11;
                    $size = $chunks * 2;
                    if($remain >= 6) 
                        $size++;
                    break;
                case QR_MODE_8:
                    $size = (int)($payload / 8);
                    break;
                case QR_MODE_KANJI:
                    $size = (int)(($payload / 13) * 2);
                    break;
                case QR_MODE_STRUCTURE:
                    $size = (int)($payload / 8);
                    break;
                default:
                    $size = 0;
                    break;
            }
            
            $maxsize = QRspec::maximumWords($mode, $version);
            if($size < 0) $size = 0;
            if($size > $maxsize) $size = $maxsize;

            return $size;
        }
        
        //----------------------------------------------------------------------
        public function createBitStream()
        {
            $total = 0;

            foreach($this->items as $item) {
                $bits = $item->encodeBitStream($this->version);
                
                if($bits < 0) 
                    return -1;
                    
                $total += $bits;
            }

            return $total;
        }
        
        //----------------------------------------------------------------------
        public function convertData()
        {
            $ver = $this->estimateVersion();
            if($ver > $this->getVersion()) {
                $this->setVersion($ver);
            }

            for(;;) {
                $bits = $this->createBitStream();
                
                if($bits < 0) 
                    return -1;
                    
                $ver = QRspec::getMinimumVersion((int)(($bits + 7) / 8), $this->level);
                if($ver < 0) {
                    throw new Exception('WRONG VERSION');
                    return -1;
                } else if($ver > $this->getVersion()) {
                    $this->setVersion($ver);
                } else {
                    break;
                }
            }

            return 0;
        }
        
        //----------------------------------------------------------------------
        public function appendPaddingBit(&$bstream)
        {
            $bits = $bstream->size();
            $maxwords = QRspec::getDataLength($this->version, $this->level);
            $maxbits = $maxwords * 8;

            if ($maxbits == $bits) {
                return 0;
            }

            if ($maxbits - $bits < 5) {
                return $bstream->appendNum($maxbits - $bits, 0);
            }

            $bits += 4;
            $words = (int)(($bits + 7) / 8);

            $padding = new QRbitstream();
            $ret = $padding->appendNum($words * 8 - $bits + 4, 0);
            
            if($ret < 0) 
                return $ret;

            $padlen = $maxwords - $words;
            
            if($padlen > 0) {
                
                $padbuf = array();
                for($i=0; $i<$padlen; $i++) {
                    $padbuf[$i] = ($i&1)?0x11:0xec;
                }
                
                $ret = $padding->appendBytes($padlen, $padbuf);
                
                if($ret < 0)
                    return $ret;
                
            }

            $ret = $bstream->append($padding);
            
            return $ret;
        }

        //----------------------------------------------------------------------
        public function mergeBitStream()
        {
            if($this->convertData() < 0) {
                return null;
            }

            $bstream = new QRbitstream();
            
            foreach($this->items as $item) {
                $ret = $bstream->append($item->bstream);
更改图片的大小比例 Resizing images with PHP
<?php
 
/*
* File: SimpleImage.php
* Author: Simon Jarvis
* Copyright: 2006 Simon Jarvis
* Date: 08/11/06
* Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details:
* http://www.gnu.org/licenses/gpl.html
*
*/
 
class SimpleImage {
 
   var $image;
   var $image_type;
 
   function load($filename) {
 
      $image_info = getimagesize($filename);
      $this->image_type = $image_info[2];
      if( $this->image_type == IMAGETYPE_JPEG ) {
 
         $this->image = imagecreatefromjpeg($filename);
      } elseif( $this->image_type == IMAGETYPE_GIF ) {
 
         $this->image = imagecreatefromgif($filename);
      } elseif( $this->image_type == IMAGETYPE_PNG ) {
 
         $this->image = imagecreatefrompng($filename);
      }
   }
   function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image,$filename,$compression);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image,$filename);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image,$filename);
      }
      if( $permissions != null) {
 
         chmod($filename,$permissions);
      }
   }
   function output($image_type=IMAGETYPE_JPEG) {
 
      if( $image_type == IMAGETYPE_JPEG ) {
         imagejpeg($this->image);
      } elseif( $image_type == IMAGETYPE_GIF ) {
 
         imagegif($this->image);
      } elseif( $image_type == IMAGETYPE_PNG ) {
 
         imagepng($this->image);
      }
   }
   function getWidth() {
 
      return imagesx($this->image);
   }
   function getHeight() {
 
      return imagesy($this->image);
   }
   function resizeToHeight($height) {
 
      $ratio = $height / $this->getHeight();
      $width = $this->getWidth() * $ratio;
      $this->resize($width,$height);
   }
 
   function resizeToWidth($width) {
      $ratio = $width / $this->getWidth();
      $height = $this->getheight() * $ratio;
      $this->resize($width,$height);
   }
 
   function scale($scale) {
      $width = $this->getWidth() * $scale/100;
      $height = $this->getheight() * $scale/100;
      $this->resize($width,$height);
   }
 
   function resize($width,$height) {
      $new_image = imagecreatetruecolor($width, $height);
      imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
      $this->image = $new_image;
   }      
 
}
?>

<?php
   include('SimpleImage.php');
   $image = new SimpleImage();
   $image->load('picture.jpg');
   $image->scale(50);
   $image->save('picture2.jpg');
?>

<?php
   if( isset($_POST['submit']) ) {
 
      include('SimpleImage.php');
      $image = new SimpleImage();
      $image->load($_FILES['uploaded_image']['tmp_name']);
      $image->resizeToWidth(150);
      $image->output();
   } else {
 
?>
 
   <form action="upload.php" method="post" enctype="multipart/form-data">
      <input type="file" name="uploaded_image" />
 
      <input type="submit" name="submit" value="Upload" />
 
   </form>
 
<?php
   }
?>

<?php
   header('Content-Type: image/jpeg');
   include('SimpleImage.php');
   $image = new SimpleImage();
   $image->load('picture.jpg');
   $image->resizeToWidth(150);
   $image->output();
?>
更改JPEG图片的DPI php Change the DPI of a Jpeg Image with PHP
<?php

//Read the jpeg image
$path = "temp/ddd.jpg";
$image = file_get_contents($path);

$image = substr_replace($image, pack("cnn", 1, 300, 300), 13, 5);

//在原图上更改
//$f = fopen($path, 'w');
//fwrite($f, $image);
//fclose($f);

//生成新图片
//header("Content-type: image/jpeg");
//header('Content-Disposition: attachment; filename="'.basename($path).'"');

echo $image;

?>
读取JPEG图片的DPI php
<?php
var_dump(jpeg_dpi("temp/aa.jpg"));
function jpeg_dpi($filename)
{
    if ( exif_imagetype($filename) != IMAGETYPE_JPEG ) {
        return false;
    } else {
        $exif = exif_read_data($filename, 'IFD0');
    }
    
    $x = $y = 0;
    if ( isset($exif['XResolution']) && isset($exif['YResolution']) ) {
        $x = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['XResolution']));
        $y = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['YResolution']));
    }
    
    if ( !$x && !$y && $fp = fopen($filename, 'r') ) {
        $string = fread($fp, 20);
        fclose($fp);
        
        $data = bin2hex(substr($string, 14, 4));
        $x = hexdec(substr($data, 0, 4));
        $y = hexdec(substr($data, 4, 4));
    }
    
    if ( $x || $y ) {
        return array($x, $y);
    }
    
    return false;
}

?>
qunit demo javascript, qunit
index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>QUnit Test Suite</title>
	<link rel="stylesheet" href="qunit/qunit.css">
	<script src="jquery-1.8.0.min.js"></script>
	<script src="qunit/qunit.js"></script>
	<script src="app.js"></script>
	<script src="test.js"></script>
</head>
<body>
<h1 id="qunit-header">QUnit Test Suite</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests">test markup, hidden.</ol>
<div id="qunit-fixture">test markup</div>
</body>
</html>


test.js

// Let's test this function
function isEven(val) {
 return val % 2 === 0;
}	 
var a=2,b=2;
//基本斷言
/**
test('isEven()', function() {
	ok(isEven(0), 'Zero is an even number');
	ok(isEven(2), 'So is two');
    ok(isEven(-4), 'So is negative four');
    ok(!isEven(1), 'One is not an even number');
	ok(!isEven(-7), 'Neither is negative seven');
	 // Fails
	ok(isEven(3), 'Three is an even number');
	//一般斷言。採用==比較
	equal(a,b,'a=b');
	//深度斷言。採用===判斷 用於判斷object,array,null,undefined等
	deepEqual({a: 1}, {a: 1} ,'object equal');
	equal(null,undefined ,'null equal');
	//fail
	deepEqual(null,undefined ,'null deepequal');
	
	//深度比較取反
	test("notDeepEqual", 2, function() {
		var actual = {q: 'foo', t: 'bar'};
		notEqual( actual, {q: 'foo', t: 'bar'}, "passes - objects are not equal" );
		notDeepEqual( actual, {q: 'foo', t: 'bar'}, "fails - objects are equivalent" );
	});
})
**/


//嚴格比較
//嚴格比較 === 參數2表示期望2個斷言
/***
test( "strictEqual", 2, function() {
	var actual = 6 - 5;
	strictEqual( actual, true, "fails as 1 !== true" );
	strictEqual( actual, 1, "passes as 1 === 1" );
});

//嚴格比較取反 等於!== 參數2表示期望2個斷言
test("notStrictEqual", 2, function() {
	var actual = 6 - 5;
	notStrictEqual( actual, true, "passes as 1 !== true" );
	notStrictEqual( actual, 1, "fails as 1 === 1" );
});
**/


//結構化
/***
module('Module A');
test('a test', function() {
	ok( true, "this test is pass" );
});
test('an another test', function() {
	equal( 2,3, "this test is failed" );
});
 
module('Module B');
test('a test', function() {
	ok( false, "this test is pass" );
});
test('an another test', function() {
	equal( 1,1, "this test is failed" );
});
**/

//異步斷言
/**
test('asynchronous test', function() {
	stop();//暫停
	setTimeout(function() {
		ok(true);
		start();//開始執行
	}, 100)
})
//等同於上面的test('asynchronous test');
asyncTest('asynchronous test', function() {
	// The test is automatically paused
	setTimeout(function() {
		ok(true);
		start();
	}, 100)
})
**/

// 異步斷言 指定斷言數量
/***
function ajax(successCallback) {
	$.get("server.php",successCallback);
}
//參數4等同於expect(4)
asyncTest('asynchronous test', 4,function() {
	ajax(function(data) {
		// ...asynchronous assertions
		equal(data,"s",'is s');
	})
	//期望執行的斷言數量
	ajax(function() {
		// ...asynchronous assertions
		ok(true,'is true');
	})
	ajax(function() {
		// ...asynchronous assertions
		ok(false,'is false');
	})
	
	setTimeout(function() {
		start();
	}, 1000)
})
***/

//拋出異常
/****
test("raises", 1, function() {
	raises(function() {
		throw new Error( "Oh no! It's an error!" );
	}, "passes - an error was thrown inside our callback");
});
**/
php使用phpqrcode生成二維碼 php, qrcode
php 生成二維碼demo

<?php
include "qrlib.php";  
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;

//html PNG location prefix 保存目錄
$PNG_WEB_DIR = 'temp/';
if (!file_exists($PNG_TEMP_DIR))
        mkdir($PNG_TEMP_DIR);  
//二維碼內容
$value="http://www.nmg.com.hk";
$errorCorrectionLevel = 'L';//質量大小。L(the smallest),M,Q,H(best)
$matrixPointSize = 4;//可設置1-10.默認4
//保存文件名
$filename = $PNG_TEMP_DIR.md5($value.'|'.$errorCorrectionLevel.'|'.$matrixPointSize).'.png';
//生成二維碼
QRcode::png($value, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
//show benchmark 顯示生成時間
QRtools::timeBenchmark();

//rebuild cache 生成cache文件保存到cache目錄
QRtools::buildCache();

//輸出二維碼圖片    
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';  


exit;
?>
获取indesign 对象的所有属性 jsx, indesign
main();


function main(){
	if(app.documents.length != 0){
		if(app.selection.length != 0){
		var txtFile= new File ("~/Desktop/obj/image.txt");
        txtFile.encoding = 'UTF-8';
        txtFile.open("w");
			//alert(app.selection[0].texts[0].color);
			getMethodAndPropertys(txtFile, app.selection[0],"|");
			txtFile.close();
		}
	}
}



function getMethodAndPropertys(file, obj, prv) {
	for (var id in obj) {
		try {
			if(id == "parent" || id == "parentPage" || id == "parentStory" || id == "startTextFrame" || id == "endTextFrame" || id=="nextTextFrame" || id=="nextStyle"){
				continue;
			}else{
				if (typeof(obj[id]) == "function") {
					file.write(prv+"."+obj[id].toString()+"\n");

} else if(typeof(obj[id]) == "object" ) {
					getMethodAndPropertys(file,obj[id],prv+"."+id);
				}else{
					file.write(prv+"." + id + ": " + obj[id].toString()+"\n");
				}
			}
		} catch (err) {
			file.write(prv+"." + id + ": inaccessible\n");
		}
	}
}
adobe create suite extention script 记录 adobe, create suite, extend, script, actionscript, jsx
1 延时(js)
$.sleep(1000);
$.writeln("testt");

2 执行脚本(as)
var url:String = getAppStoragePath() + "assets/post.jsx";
var back:Object = app.doScript(url, ScriptLanguage.javascript, myArg);
第二种方式(推荐)
package 
{
	import flash.external.HostObject;
	public class HelloCreativeSuiteJSX
	{	
		[Embed(source="./HelloCreativeSuite.jsx", mimeType="application/octet-stream")]

		private static var EsInitClass: Class;
		public static function run():void 
		{
			var scriptObject: Object = new EsInitClass();

			var initScript: String = scriptObject.toString();

			var myBridgeScript : HostObject = HostObject.getRoot(HostObject.extensions[0]);
			myBridgeScript.eval(initScript);
			var jsxReturnStr : String =  myBridgeScript.sayHello();
			trace(jsxReturnStr);
		}
	}
}

3 创建模式面板,非模式面板和提示
public function showModal():void
{
	var window:Window = new ModalDialog;
	window.type = CSXSWindowType.MODAL_DIALOG;
	window.resizable = false;
	window.open();
}
public function showModeless():void
{
	var modelessWindow:Window = new ModelessDialog;
	modelessWindow.type = CSXSWindowType.MODELESS;
	modelessWindow.open();
}
public function showTooltip():void
{
	var tooltipWindow:Window = new ToolTip;
	tooltipWindow.type = CSXSWindowType.TOOLTIP;
	tooltipWindow.open();
}

4 创建面板菜单
private const MENU_SHOW_MODAL:String = "Display Modal Dialog";
private const MENU_SHOW_MODELESS:String = "Display Modeless Dialog";
private const MENU_SHOW_TOOLTIP:String = "Display ToolTip Window";

public var xmlBasicMenu:XML =
	<Menu>
	 <MenuItem Label={MENU_SHOW_MODAL}/>
	 <MenuItem Label={MENU_SHOW_MODELESS}/>
	 <MenuItem Label={MENU_SHOW_TOOLTIP}/>
	</Menu>
CSXSInterface.instance.addEventListener(MenuClickEvent.FLYOUT_MENU_CLICK, menuClickHandler);
var menuAdded:SyncRequestResult = CSXSInterface.instance.setPanelMenu(xmlBasicMenu);
if(SyncRequestResult.COMPLETE != menuAdded.status){
	showAlert("initializeMenu() Failed to add menu");	
}	

5 创建CSXS面板标签
<csxs:CSXSWindowedApplication>
可设置面板title和底部的toolbar

6 获取当前语言环境(hostEnvironment也包含了当前应用类型,如indesign,photoshop。
hostEnv.appName
hostEnv.isAppOffline 是否在线
appLocale 语言
appVersion 版本)

[Bindable]
private var currentUILocale:String;

private function onCreationComplete() : void
{	
	var result : SyncRequestResult = CSXSInterface.getInstance().initResourceBundle();

	if (result.status != SyncRequestResult.COMPLETE)
	{
		trace(result.status + ": " + result.data.toString());
	}

	result = CSXSInterface.instance.getHostEnvironment();
	var hostEnvironment : HostEnvironment = result.data as HostEnvironment;
	currentUILocale = hostEnvironment.appUILocale;
}		

7 通过HTTPRequest提交http请求和参数并获取返回值
import com.adobe.awsi.HttpRequest;
import com.adobe.awsi.HttpResponse;
/**
 * Uses the AWSI libraries to connect to the Google Translate APIs to:
 * 1) Determine if the current language combination is supported
 * 2) If supported translates the passed text
 * @param text	the selection of text to be translated
 * @param lang	what language to translate it too
 * @param onSucccess callback function to return translated string
 */ 
public function useGoogleApis(text:String, lang:String, onSuccess:Function, onError:Function=null):void
{
	var request:HttpRequest = new HttpRequest(HttpRequest.GET, "http://ajax.googleapis.com/ajax/services/language/detect", "");
	request.setParam("v", "1.0");
	request.setParam("q", text);
	request.perform(function(response:HttpResponse):void
	{
		if((response.succeeded() || response.get_Status() == 0) && (response.isParseable() && response.getRootNode().child_text("responseStatus") == "200"))
		{
			var language:String = response.getRootNode().child("responseData").child_text("language");
			
			// now try translation API
			var translateRequest:HttpRequest = new HttpRequest(HttpRequest.GET, "http://ajax.googleapis.com/ajax/services/language/translate", "");
			translateRequest.setParam("q", text);
			translateRequest.setParam("v", "1.0");
			var langpair:String = language + "|" + lang;
			translateRequest.setParam("langpair", langpair);
			translateRequest.perform(function(translateResponse:HttpResponse):void
			{
				if((translateResponse.succeeded() || translateResponse.get_Status() == 0) && (translateResponse.isParseable() && translateResponse.getRootNode().child_text("responseStatus") == "200"))
				{
					onSuccess(translateResponse.getRootNode().child("responseData").child_text("translatedText"));
				}
				else
				{
					// error - translation not supported
					onError("The translation from " + language + " to " + lang + " is not supported");
				}
			});
		}	
		else
		{
			onError("Sorry but something went wrong");
		}
	});
}
参考 BASERSSReader
8 判断网络是否可用(as)
/**
 * Determines if the Creative Suite product has a network
 * connection
 */ 
public function computeOnline():void
{
	var res:Boolean = false;
	var result:SyncRequestResult = CSXSInterface.getInstance().getNetworkPreferences();
	var networkPreferences:NetworkPreferences;
	
	if ((result.status == SyncRequestResult.COMPLETE) && result.data)
	{
		networkPreferences = result.data as NetworkPreferences;
		if (networkPreferences.overallOnlinePreference)
		{
			//online preference are enabled, so go online
			res = true;
		}
	}
	this.getModel().online = res;
	if (this.getModel().online == false)
	{
		this.getModel().notifier = "Polyglot is unavailable due to lack of network access";
	}
}

9 XMPMETA DATA 操作(as)
创建XMPMeta 必须指定命名空间来访问
var meta:XMPMeta = new XMPMeta();
//var xmp:Namespace = new Namespace("http://ns.adobe.com/xap/1.0/");
var nmg:Namespace = new Namespace("my", "http://com.nmg.xmp/");
meta.nmg::CreatorTool = "Indesign";//设置属性CreatorTool为Indesign

//下面是2个命名空间
meta.xmpNS::Rating = 4;
meta.my::simpleProp = "value";

读取属性
trace(meta.xmpNS::Rating);  // shows "4"
trace(meta.my::simpleProp); // shows "value"

更新属性
meta.xmpNS::Rating = 5;
meta.my::simpleProp = "new value";

删除属性
meta.my::simpleProp = null;
—or—
delete meta.my::simpleProp;

判断属性是否存在
trace( meta.xmpNS::Rating.exists() );     // true
trace( meta.my::simpleProp.exists() );    // false
trace( meta.my::simpleProp.toString() );  // null

数据类型转换
The XMPMeta object provides convenience methods for retrieving String property values as literal types:
toBoolean()
toInteger()
toFloat()
toDate()

添加结构化XMP属性(对象属性)
var effect:Namespace = new Namespace("effect","http://com.nmg.xmp.effect/");
var struct:XMPStruct = new XMPStruct();
struct.effect::effectId = "1";
struct.effect::effectType = "slideshow";
// add the structured property to the XMP object
meta.nmg::struct = struct;
// Retrieve a struct field
Log.add (meta.nmg::struct.effect::effectType);
删除结构化XMP属性
meta.nmg::struct = null
—or—
delete meta.nmg::struct

添加数组属性
以下三种添加类型
meta.my::bagArray = XMPArray.newBag();// 保存字符串
meta.my::seqArray = XMPArray.newSeq();
meta.my::altArray = XMPArray.newAlt();//保存struct对象结构
添加数组元素方式
To add items, use the square brackets, "[...]" operator, or the append() and insert() methods of the XMPArray object.  
获取最后一个元素
The special index value "last()" accesses the last item: meta.my::bagArray ["last()"].
trace(meta.my::seqArray[5]); // prints "five"
trace(meta.my::seqArray["last()"]); // prints "five"
length();获取数组长度 

通过对象方式设置array
meta.nmg::effectArray = XMPArray.newAlt();
var effectArray:XMPArray = new XMPArray();
effectArray.setType(2);//0:newBag,1:newSeq,2:newAlt
effectArray.append(struct);
effectArray.append(struct2);
meta.nmg::effectArray = effectArray;
注意:不能通过effectArray[1]的方式访问子节点。XMPArray.toString()和struct.toString()(输出<struct>)都无法获取到对应的字符串内容。

输出XMPMETADATA
var metaStr:String = meta.serialize();
var metaBuffer:ByteArray = meta.serializeToBuffer();
var metaXML:XML = meta.serializeToXML();

遍历XMP METADATA
Iterate through all property values of a structured property:
for each (var prop: XMPNode in meta.my::struct)
{
   trace(prop);
}
Iterate through all property names of a structured property:
for (var propName: String in meta.my::struct)
{
   trace(prop);
}
Iterate through the names of all top-level properties:
for (var propName: String in meta)
{
   trace(prop);
}
Iterate through all items of an array property:
for each (var prop: XMPNode in meta.my::array)
{
   trace(prop);
}

10 不通过XMP存储数据(as)
CSXS提供了一种存储和读取的机制,可以再indesign重启后依然能拿到数据。只能存储string类型。
通过ID识别。ID通过AMF转换再转换为BASE64格式的字符串。
可设置是否与其它extention扩展共享数据。
这种机制不支持在不同的电脑中共享数据。只针对当前电脑的indesign。
参考CSXSPrefBase demo项目
/**
 * Repopulates the object associated with <code>preferenceID</code>.
 **/
public function retrieve(preferenceID:String):void {
	//make CSXS call to retrieve preference	
	var result:SyncRequestResult = CSXSInterface.getInstance().retrievePreference(preferenceID);
	if (result.status == SyncRequestResult.COMPLETE && result.data) {
		decode(result.data as String);
	} else {
		throw new Error("Could not retrieve object with id " + preferenceID + ".");
	}
}
/**
 * Repopulates the shared object associated with <code>preferenceID</code>.
 **/
public function retrieveShared(preferenceID:String):void {
	//make CSXS call to retrieve shared preference			
	var result:SyncRequestResult = CSXSInterface.getInstance().retrieveSharedPreference(preferenceID);
	if (result.status == SyncRequestResult.COMPLETE && result.data) {
		decode(result.data as String);
	} else {
		throw new Error("Could not retrieve object with id " + preferenceID + ".");
	}
}

/**
 * Stores the object with the key <code>preferenceID</code>. If no <code>preferenceID</code> is provided a unique one is automatically generated. 
 * Returns the <code>preferenceID</code> associated with the object.
**/ 
public function store(preferenceID:String = null):String {
	//if key hasn't been set, set one.
	if (preferenceID == null) {
		preferenceID = UIDUtil.createUID();
	}
	
	//make CSXS call to store preference	
	CSXSInterface.getInstance().storePreference(preferenceID, encode());
	return preferenceID;
}

/**
 * Stores the shared object with the key <code>preferenceID</code>. If no <code>preferenceID</code> is provided a unique one is automatically generated. 
 * Returns the <code>preferenceID</code> associated with the object.
 **/ 
public function storeShared(preferenceID:String = null):String {
	//if key hasn't been set, set one.
	if (preferenceID == null) {
		preferenceID = UIDUtil.createUID();
	}
	
	//make CSXS call to store shared preference	
	CSXSInterface.getInstance().storeSharedPreference(preferenceID, encode());
	return preferenceID;
}

11 判断当前选择物件的类型(as)
app.selection[counter] is Rectangle:
app.selection[counter] is Oval:
app.selection[counter] is Polygon:
app.selection[counter] is GraphicLine:
app.selection[counter] is TextFrame:

12 事件类型及监听(as)
//Add CSXS "standardized" events.
var myCSXS:CSXSInterface = CSXSInterface.getInstance();
myCSXS.addEventListener("documentAfterActivate", eventHandler);
myCSXS.addEventListener("documentAfterDeactivate", eventHandler);
myCSXS.addEventListener("applicationActivate", eventHandler);
//Add CSXS events.
myCSXS.addEventListener(StateChangeEvent.WINDOW_OPEN, eventHandler);
myCSXS.addEventListener(StateChangeEvent.WINDOW_SHOW, eventHandler);

//参考EVENT WATCHER demo
eventList.addItem( new EventRecord( "After Activate", Event.AFTER_ACTIVATE, false ) );
eventList.addItem( new EventRecord( "After Attibute Changed", MutationEvent.AFTER_ATTRIBUTE_CHANGED, false ) );
eventList.addItem( new EventRecord( "After Close", Event.AFTER_CLOSE, false ) );
eventList.addItem( new EventRecord( "After Context Changes", Event.AFTER_CONTEXT_CHANGED, false ) );
eventList.addItem( new EventRecord( "After Delete", Event.AFTER_DELETE, false ) );
eventList.addItem( new EventRecord( "After Embed", Event.AFTER_EMBED, false ) );
eventList.addItem( new EventRecord( "After Invoke", Event.AFTER_INVOKE, false ) );
eventList.addItem( new EventRecord( "After Links Changed", Event.AFTER_LINKS_CHANGED, false ) );
eventList.addItem( new EventRecord( "After Move", Event.AFTER_MOVE, false ) );
eventList.addItem( new EventRecord( "After New", Event.AFTER_NEW, false ) );
eventList.addItem( new EventRecord( "After Open", Event.AFTER_OPEN, false ) );
eventList.addItem( new EventRecord( "After Place", Event.AFTER_PLACE, false ) );
eventList.addItem( new EventRecord( "After Print", PrintEvent.AFTER_PRINT, false ) );
eventList.addItem( new EventRecord( "After Quit", Event.AFTER_QUIT, false ) );
eventList.addItem( new EventRecord( "After Revert", DocumentEvent.AFTER_REVERT, false ) );
eventList.addItem( new EventRecord( "After Save", DocumentEvent.AFTER_SAVE, false ) );
eventList.addItem( new EventRecord( "After Save a Copy", DocumentEvent.AFTER_SAVE_A_COPY, false ) );
eventList.addItem( new EventRecord( "After Save As", DocumentEvent.AFTER_SAVE_AS, false ) );
eventList.addItem( new EventRecord( "After Selection Attribute Changed", Event.AFTER_SELECTION_ATTRIBUTE_CHANGED, false ) );
eventList.addItem( new EventRecord( "After Selection Changed", Event.AFTER_SELECTION_CHANGED, false ) );
eventList.addItem( new EventRecord( "After Unembed", Event.AFTER_UNEMBED, false ) );
eventList.addItem( new EventRecord( "After Update", Event.AFTER_UPDATE, false ) );
eventList.addItem( new EventRecord( "Before Close", Event.BEFORE_CLOSE, false ) );
eventList.addItem( new EventRecord( "Before Deactivate", Event.BEFORE_DEACTIVATE, false ) );
eventList.addItem( new EventRecord( "Before Delete", Event.BEFORE_DELETE, false ) );
eventList.addItem( new EventRecord( "Before Display", Event.BEFORE_DISPLAY, false ) );
eventList.addItem( new EventRecord( "Before Embed", Event.BEFORE_EMBED, false ) );
eventList.addItem( new EventRecord( "Before Invoke", Event.BEFORE_INVOKE, false ) );
eventList.addItem( new EventRecord( "Before Move", Event.BEFORE_MOVE, false ) );
eventList.addItem( new EventRecord( "Before Place", Event.BEFORE_PLACE, false ) );
eventList.addItem( new EventRecord( "Before Print", PrintEvent.BEFORE_PRINT, false ) );
eventList.addItem( new EventRecord( "Before Quit", Event.BEFORE_QUIT, false ) );
eventList.addItem( new EventRecord( "Before Revert", DocumentEvent.BEFORE_REVERT, false ) );
eventList.addItem( new EventRecord( "Before Save", DocumentEvent.BEFORE_SAVE, false ) );
eventList.addItem( new EventRecord( "Before Save a Copy", DocumentEvent.BEFORE_SAVE_A_COPY, false ) );
eventList.addItem( new EventRecord( "Before Save As", DocumentEvent.BEFORE_SAVE_AS, false ) );				
eventList.addItem( new EventRecord( "Before Unembed", Event.BEFORE_UNEMBED, false ) );
eventList.addItem( new EventRecord( "Before Update", Event.BEFORE_UPDATE, false ) );
eventList.addItem( new EventRecord( "On Idle", IdleEvent.ON_IDLE, false ) );

13 写入文件的XMP metadata(js)
注意:若当前文件正在打开,则无法写入。
// load the XMPScript library
if (ExternalObject.AdobeXMPScript == undefined)
    ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');

var filePath = "/C/Users/davidhuang/Documents/未命名-2.indd";
var file = new File(filePath);
 var xmpFile = new XMPFile(file.fsName, XMPConst.UNKNOWN,XMPConst.OPEN_FOR_UPDATE);//XMPConst.OPEN_FOR_UPDATE
var xmp = xmpFile.getXMP();
// delete existing authors and add a new one
// existing metadata stays untouched
xmp.deleteProperty(XMPConst.NS_DC, "creator");
xmp.appendArrayItem(XMPConst.NS_DC, "going", "DAVIDTEST", 0,XMPConst.ARRAY_IS_ORDERED);
xmp.appendArrayItem(XMPConst.NS_DC, "creator", "INDESIGN", 0,XMPConst.ARRAY_IS_ORDERED);
// write updated metadata into the file
if (xmpFile.canPutXMP(xmp)) {
    xmpFile.putXMP(xmp);
}

xmpFile.closeFile(XMPConst.CLOSE_UPDATE_SAFELY);

14 提取文件的XMP数据并保存到xml文件(js)
//load XMP Library
var XMPload = Boolean(false);
if (ExternalObject.AdobeXMPScript == undefined){
    try {
        ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript'); 
        XMPload = true;
    }catch(ex) 
    {
        alert("Unable to load the AdobeXMPScript library!");
    }
}
if(XMPload){
    var myFile = File(app.selection[0].graphics[0].itemLink.filePath);//获取当前选择的第一个图片文件路径
    xmpFile = new XMPFile(myFile.fsName, XMPConst.UNKNOWN, XMPConst.OPEN_FOR_READ);
    xmp = xmpFile.getXMP();
    var myXmp = xmp.serialize();
    $.writeln(myXmp);//输出XMPDATA
    xmpFile.closeFile(XMPConst.CLOSE_UPDATE_SAFELY);
}
writeXMP(myXmp, File('/e/myxmp.xml'));//保存到指定文件。需先创建文件

function writeXMP(xmpData, xmpFile){
	xmpFile.open ( 'w', 'Text');
	xmpFile.encoding = 'UTF-8';
	xmpFile.write (xmpData);
	xmpFile.close ();
}

15 给当前文档的添加新的xmp 属性(js as)
var myDocXMP = app.activeDocument.metadataPreferences;
var destNamespace = "http://ns.adobe.com/xap/1.0/";//这是xmp已存在的命名空间。若输入一个不存在的命名空间则不会添加成功
var destNodeName = "MyTesting";
var nodeValue = "IndiSnip test value";
myDocXMP.setProperty(destNamespace, destNodeName, nodeValue);

as代码实现
private function fileInfo():void{
	var fileInfo:FileInfoLibrary = new FileInfoLibrary();
	var doc:Document = InDesign.app.activeDocument;
	var metaData:MetadataPreference = doc.metadataPreferences;
	var effect:Namespace = new Namespace("effect","http://com.nmg.xmp.effect/");
	var destNamespace:String = "http://ns.adobe.com/xap/1.0/";
	metaData.setProperty(destNamespace,"abc","ddd");
}

16 给当前文档的添加新的xmp 容器(js as)
var myDocXMP = app.activeDocument.metadataPreferences;
var destNamespace = "http://ns.adobe.com/xap/1.0/";
var destContName = "IndiSnip";
myDocXMP.createContainerItem(destNamespace, destContName, undefined, ContainerType.BAG);
输出:
 <xmp:IndiSnip>
	<rdf:Bag>
	   <rdf:li/>
	</rdf:Bag>
 </xmp:IndiSnip>
 
 as版本
 private function fileInfo():void{
	var doc:Document = InDesign.app.activeDocument;
	var metaData:MetadataPreference = doc.metadataPreferences;
	var destNamespace:String = "http://com.nmg.xmp.effect/";
	var orgNS:String = "http://ns.adobe.com/xap/1.0/";
	var destContName:String = "nmgEffect";
	metaData.createContainerItem(destNamespace,destContName,0,ContainerType.ALT);//无法新增 。无此命名空间

	metaData.setProperty(orgNS,"effectId","1");//新增属性成功
	metaData.setProperty(destNamespace,"effectType","slideshow");//失败。无此命名空间
	Log.add(metaData.getProperty(orgNS,"effectId"));//读取属性
	doc.save();
//输出
//				<xmp:nmgEffect>
//					<rdf:Alt>
//					   <rdf:li/>
//					</rdf:Alt>
//				 </xmp:nmgEffect>
}

注意:不能通过新增的命名空间添加属性。无法创建新的命名空间。

17 打开idnn文件并注册XMP 命名空间添加属性。(js)
注意:若该文件已经打开则运行失败。
// load XMP Library
function loadXMPLibrary(){
    if ( !ExternalObject.AdobeXMPScript ){
        try{ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');}
        catch (e){alert('Unable to load the AdobeXMPScript library!'); return false;}
    }
    return true;
}

// select destination file
var myFile = File.openDialog("Select destination file", "InDesign:*.indd", false);

// check library and file
if(loadXMPLibrary() && myFile != null){
    xmpFile = new XMPFile(myFile.fsName, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_UPDATE);
    var myXmp = xmpFile.getXMP();
}

if(myXmp){
    var destNamespace = "http://indisnip.wordpress.com/";
    // define new namespace
    XMPMeta.registerNamespace(destNamespace,"IndiSnipXMP");
    // insert nodes
    myXmp.setProperty(destNamespace,"creator","IndiSnip");
    myXmp.setProperty(destNamespace,"e-mail","indisnip@gmail.com");
    myXmp.setProperty(destNamespace,"web_site","http://indisnip.wordpress.com");
    myXmp.setProperty(destNamespace,"Version","1.0b");
    // put XMP into file
    if (xmpFile.canPutXMP(myXmp)){xmpFile.putXMP(myXmp);}else{alert("Error storing XMP");}
    // close file
    xmpFile.closeFile(XMPConst.CLOSE_UPDATE_SAFELY);
}

18 AS执行js脚本的另一种方式
//$.sleep是js脚本表示暂停
var result: SyncRequestResult = CSXSInterface.getInstance().evalScript( "$.sleep", "1" );
document.execCommand的執行代碼demo javascript, execcommand
<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
  <script src="../lib/jquery.js" type="text/javascript" charset="utf-8"></script>
  
  <script type="text/javascript" charset="utf-8">
    (function($){
      var selectedText = function(){
        if (document.selection) {
          return document.selection.createRange().text;
        } else {
          return document.getSelection().toString();
        }
      };

      var selectTest = function(){
        if (selectedText().length == 0) {
          alert("Select some text first.");
          throw "No selection";
        }
      };

      $.fn.exec = function(type, arg){    
        document.execCommand(type, false, arg || null);
        return this;
      };

      $.fn.wysiwyg = function(){
        var element = $(this);
        element.attr("contentEditable", true);

        var bold = function(){
          element.exec("bold");
        };

        var italic = function(){
          element.exec("italic");
        };

        var list = function(){
          element.exec("insertUnorderedList");
        };

        var link = function(){
          selectTest();

          element.exec("unlink");
          var href = prompt("Enter a link:", "http://");
          if ( !href || href == "http://" ) return;
          if ( !(/:\/\//).test(href) ) href = "http://" + href;
          element.exec("createLink", href);
        };

        var val = function(){
          return element.html();
        };
			
		var print = function(){
			element.exec("print");
		};
		//saveas無法執行
		var save = function(){
			alert("dd");
			element.exec("saveas",true,'mycodes.txt');
		};
		var selectAll = function(){
			element.exec("selectAll");
		};
        return({
          bold:   bold,
          italic: italic,
          list:   list,
          link:   link,
          val:    val,
		  print:  print,
		  save: save,
		  selectAll:selectAll
        });
      };
    })(jQuery);
  </script>
  
  <script type="text/javascript" charset="utf-8">
    jQuery(function($){
      var controls = $("#editor").wysiwyg();
      
      $("#controls").delegate("a", "click", function(){
        controls[$(this).attr("data-type")]();
        return false;
      });
    })
  </script>
  
  <style type="text/css" media="screen">
    #editor {
      padding: 5px;
      border: 1px solid #000;
      min-height: 200px;
    }
  </style>
</head>
<body>
  <div id="controls">
    <a href="#" data-type="bold">Bold</a>
    <a href="#" data-type="italic">Italic</a>
    <a href="#" data-type="list">List</a>
    <a href="#" data-type="link">Link</a>
	<a href="#" data-type="print">Print</a>
	<a href="#" data-type="save">Save As</a>
	<a href="#" data-type="selectAll">Select All</a>
  </div>
  <div id="editor"></div>
</body>
</html>
javascript閉包例子及解決方法 javascript, 闭包 http://www.jb51.net/article/26553.htm
<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8" />
		<title>闭包演示</title>
		<style type="text/css">
			p {
				background: gold;
			}
		</style>
		<script type="text/javascript">
			//閉包的例子。onload訪問init並調用了init中onlick的匿名函數,最後輸出的i全部都是5
			//解決:
			//将变量 i 保存给在每个段落对象(p)上
			function init1() {
				var pAry = document.getElementsByTagName("p");
				for (var i = 0; i < pAry.length; i++) {
					pAry[i].i = i;
					pAry[i].onclick = function() {
						alert(this.i);
					}
				}
			}

			//将变量 i 保存在匿名函数自身
			function init2() {
				var pAry = document.getElementsByTagName("p");
				for (var i = 0; i < pAry.length; i++) {
					(pAry[i].onclick = function() {
						alert(arguments.callee.i);
					}).i = i;
				}
			}

			//加一層閉包
			function init3() {
				var pAry = document.getElementsByTagName("p");
				for (var i = 0; i < pAry.length; i++) {
					(function(arg) {
						pAry[i].onclick = function() {
							alert(arg);
						};
					})(i);
					//调用时参数
				}
			}

			//加一层闭包,i 以局部变量形式传递给内层函数
			function init4() {
				var pAry = document.getElementsByTagName("p");
				for (var i = 0; i < pAry.length; i++) {
					(function() {
						var temp = i;
						//调用时局部变量
						pAry[i].onclick = function() {
							alert(temp);
						}
					})();
				}
			}

			//加一层闭包,返回一个函数作为响应事件(注意与3的细微区别)
			function init5() {
				var pAry = document.getElementsByTagName("p");
				for (var i = 0; i < pAry.length; i++) {
					pAry[i].onclick = function(arg) {
						return function() {//返回一个函数
							alert(arg);
						}
					}(i);
				}
			}
			//用Function实现,实际上每产生一个函数实例就会产生一个闭包 
			function init6() {
				var pAry = document.getElementsByTagName("p");
				for (var i = 0; i < pAry.length; i++) {
					pAry[i].onclick = new Function("alert(" + i + ");");
					//new一次就产生一个函数实例
				}
			}
			//用Function实现,注意与6的区别 
			function init7() { 
				var pAry = document.getElementsByTagName("p"); 
				for( var i=0; i<pAry.length; i++ ) { 
					pAry[i].onclick = Function('alert('+i+')'); 
				} 
			} 
			function init() {
				var pAry = document.getElementsByTagName("p");
				for (var i = 0; i < pAry.length; i++) {
					pAry[i].onclick = function() {
						alert(i);
					}
				}
			}
		</script>
	</head>
	<body onload="init6();">
		<p>
			产品 0
		</p>
		<p>
			产品 1
		</p>
		<p>
			产品 2
		</p>
		<p>
			产品 3
		</p>
		<p>
			产品 4
		</p>
	</body>
</html>
使用fsockpoen模拟post请求 php, socket, post
client.php
<?php  
$domain = "127.0.0.1";  
$port = 80;  
$uri = "/server/http.php";  
$data="data=david&txtName=111&txtEmail=222@1.net&rabSex=%D0%A1%BD%E3&txtFrom=%BD%AD%CE%F7%C1%FA%C4%CF&txtQq=2222&txtUrl=33333333&txtFace=images%2Fface%2Fface05.gif&txtEm=images%2Fem%2Fem01.gif&txtBody=rrr";  
$protocolstr ="POST {$uri} HTTP/1.1\r\nHost: {$domain}\r\nContent-type: application/x-www-form-urlencoded\r\nContent-length: " . strlen($data) . "\r\nReferer: http://10.10.10.10/ly/index.php\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322)\r\nAccept: */*\r\n\r\n{$data}\r\n\r\n";  
  
  
$sock = fsockopen($domain, $port, $errno, $errstr, 30);  
if (!$sock) die("$errstr ($errno)\n");  
fputs($sock, $protocolstr);  
  
$headers = "";  
while ($str = trim(fgets($sock, 4096)))  
  $headers .= "$str\n";  
  
$body = "";  
while (!feof($sock))  
  $body .= fgets($sock, 4096);  
fclose($sock);  
  
echo "<h2>Response header:</h2>\n";  
echo $headers;  
echo "\n";  
  
echo "<h2>Response body:</h2>\n";  
echo $body;  
?>  
http.php

<?php
	$data = $_POST["data"];
	if($_POST['data']){
		echo $_POST['data'];
	}else{
		echo "no data";		
	}
?>
	
2个表数据更新插入的sql mysql
--
-- 将 `zz_customer`的name更新到zz_yscustomer
--
update zz_yscustomer,zz_customer set zz_yscustomer.NAME=zz_customer.name where zz_yscustomer.id = zz_customer.id;

update zz_yscustomer,zz_customer set zz_yscustomer.address=zz_customer.address where zz_yscustomer.id = zz_customer.id;
--
-- 将 `zz_customer`的name插入到zz_yscustomer
--
insert into zz_yscustomer (id,name,address)  ( select id, name,address from zz_customer where zz_customer.id >20);


在SQLyog中删除一张表时候,出现

Error No. 1451
Cannot delete or update a parent row: a foreign key constraint fails (...)

这可能是MySQL在InnoDB中设置了foreign key关联,造成无法更新或删除数据。可以通过设置FOREIGN_KEY_CHECKS变量来避免这种情况。
SET FOREIGN_KEY_CHECKS = 0;
删除完成后设置
SET FOREIGN_KEY_CHECKS = 1;

清空表数据
truncate TABLE ZZ_STAFF

查询数据库中表的数量
SELECT count(*) TABLES, table_schema FROM information_schema.TABLES
where table_schema = 'education' GROUP BY table_schema;
education改为自己的数据库名

基于backbone的helloworld backbone, javascript, mvc, underscore
<!DOCTYPE html>
<html>
	<head> 
	    <title>the5fire.net-backbone.js-Hello World</title> 
	</head> 
	<body>
		<button id="check">报到</button> 
		<ul id="world-list"> 
		     
		</ul> 
	</body>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
	<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script> 
	<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script> 
	<script type="text/javascript">
		(function($){
			//创建World对象。拥有name属性
			var World = Backbone.Model.extend({
				name:null
			})
			//World集合 
			var WorldList = Backbone.Collection.extend({
				initialize:function(models,options){
					this.bind("add",options.view.addOneWorld);
				}
			})
			var AppView = Backbone.View.extend({
				el:$("body"),
				initialize:function(){
					 //构造函数,实例化一个World集合类,并且以字典方式传入AppView的对象
					this.worldList = new WorldList(null,{view:this});
				},
				events:{
					"click #check":"checkin",//事件绑定,绑定Dom中id为check的元素
				},
				checkin:function(){
					var world_name = prompt("what is your name?");
		            if(world_name == "") world_name = '未知';
		            var world = new World({ name: world_name });
		            this.worldList.add(world);
				},
				addOneWorld:function(model){
					$("#world-list").append("<li>这里是来自 <b>" + model.get('name') + "</b>的问候:hello world!</li>");
				}
			})
			var app = new AppView;
		})(jQuery);
	</script>
</html>
js复制粘贴 javascript
<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
  
  <script src="../lib/jquery.js" type="text/javascript" charset="utf-8"></script>
    
  <script type="text/javascript" charset="utf-8">
    jQuery(function($){
	//包括键盘的ctrl+c ctrl+v 和鼠标右键都生效。FF不支持。Chrome支持
		//复制事件
      $("body").bind("copy", function(event){
        event.stopPropagation();
        event.preventDefault();
                
        var cd = event.originalEvent.clipboardData;
        cd.setData("text/plain", "who goes there?");//重设剪切板的内容
      })
	  //粘帖事件
      $('body').bind('paste', function(event){
        event.preventDefault();
        var clipboardData = event.originalEvent.clipboardData.getData('text/plain');
        console.log(clipboardData);
      }); 
    })  
  </script>
</head>
<body>
  <textarea id="copyzone" placeholder="copy here"></textarea>
</body>
</html>
js的状态机 javascript
<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
  <script src="../lib/jquery.js" type="text/javascript" charset="utf-8"></script>
  
  <script type="text/javascript" charset="utf-8">
    var Events = {
      bind: function(){
        if ( !this.o ) this.o = $({});
        this.o.bind.apply(this.o, arguments);
      },
      
      trigger: function(){
        if ( !this.o ) this.o = $({});
        this.o.trigger.apply(this.o, arguments);
      }
    };
    
    var StateMachine = function(){};
    StateMachine.fn  = StateMachine.prototype;
    $.extend(StateMachine.fn, Events);
    
    StateMachine.fn.add = function(controller){
      this.bind("change", function(e, current){
        if (controller == current)
          controller.activate();
        else
          controller.deactivate();
      });
      
      controller.active = $.proxy(function(){
        this.trigger("change", controller);
      }, this);
    };
    
    var con1 = {
      activate: function(){ 
        console.log("controller 1 activated");
      },
      deactivate: function(){ 
        console.log("controller 1 deactivated");
      }
    };
    
    var con2 = {
      activate: function(){ 
        console.log("controller 2 activated");
      },
      deactivate: function(){ 
        console.log("controller 2 deactivated");
      }
    };
    
    var sm = new StateMachine;
    sm.add(con1);
    sm.add(con2);
    
    con1.active();
  </script>
</head>
<body>
  
</body>
</html>
js生成guid guid
Math.guid = function(){
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
  }).toUpperCase();      
};
用一个表的字段更新一个表
MySQL 数据库把一个表的数据插入到另一个表实操 
用一个表的字段更新一个表
一般插入记录则可以

insert into table2 select * from table1;

更新则

update table1 inner join talbe2 on table1.col=table2.col
set table1.coln=talbe2.coln
simpleXML解析XML文件,存在问题 php simplexml
<?php
$fileArr = array (
	"06 movie_2012_4_24_10_31_22"
);
$fileArr = array (
	"06 movie_2012_4_24_10_31_22"
);
$xmlArr = array (
	"Folio.xml"
);
readXml("Folio.xml");
//删除目录或文件名的空格
function getDirs() {
	foreach ($fileArr as $file) {
		$newfile = replaceSpace($file);
		if ($newfile) {
			get_dir_scandir($newfile);
		}
	}
}

//遍历文件夹
function get_dir_scandir($path) {
	foreach (scandir($path) as $single) {
		if ($single != '.' && $single != '..') { //不是根目录
			$path2 = $path . '/' . $single;
			echo $path2 . "<br/>";
			replaceSpace($path2); //更改文件或目录名称
			if (is_dir($path2)) { //是否目录
				get_dir_scandir($path2);
			}
		}
	}
}

//删除文件夹或文件名的空格
function replaceSpace($file) {
	$newfile = str_replace(' ', '', trim($file)); //替换空格
	if ($newfile != $file) {
		if (!file_exists($newfile)) { //判断文件或文件夹是否存在
			rename($file, $newfile); //重命名。。若已存在该文件名则会报错。。若路径不正确也会报错
			echo "change!" . $newfile;
		} else {
			echo "已经存在";
		}
		return $newfile;
	}
}

function replaceStr($str) {
	$newstr = str_replace(' ', '', trim($str)); //替换空格
	return $newstr;
}
//遍历节点
function iterateNode($node) {
	if (count($node->children()) == 0) {
		echo "dfd";
	} else {
		foreach ($node->children() as $child) {
			$sub = $child->getName(); //子节点名称
			$child = replaceStr($child); //更改值
			$subs = $node-> $sub;
			if (count($subs) > 1) { //如果存在多个相同的子节点,则只会更改第一个节点的属性。因此要遍历更改
				foreach ($subs as $i) {
					iterateAttr($i); //更改属性
				}
			} else {
				iterateAttr($node-> $sub); //更改属性
			}
			if (count($node->children()) == 0) {
				@ $node-> $sub = replaceStr($sub); //会有warning提示。$node->$sub是数组类型。
			} else {
				$num = count($node-> $sub);
				if ($num > 1) { 
//如果存在多个相同的子节点,则只会遍历第一个节点。
					//$node->rectangle[1] 和 $node->$sub[1] 虽然$sub等于rectangle,但是这两者是不同的类型,
					//第一个返回的是节点的值,而第二个返回的是一个空的simpleXML对象 SimpleXMLElement。
					//可以通过xpath查询出节点的值,但是不能通过给xpath赋值改变节点的值。
					for($i=0;$i<$num;$i++){
						//$node-> $sub[$i] = "aa";
						//$b = "rectangle";
						//var_dump($node->$b[1]);
//						$node->$b-> = "ccc";
//						@$subxpath[$i] = replaceStr($subxpath[$i]);			
//						echo $subxpath[$i];
//						if(count($node->$sub->children()) == 0){
//							$n = $node->$sub[$i];
//							@$n = replaceStr($n);							
//						}else{
//							iterateNode($node->$sub[$i]);
//						}
					}
					//$node = "aa";
					//var_dump($node->xpath("//$sub")) ;
//					while(list($key,$val) = each($node->$sub)){
//						
//						if($num == 0){//没有子节点
//							@ $val = replaceStr($val); //会有warning提示。$node->$sub是数组类型。
//							echo $val."<br />";
//						}else{
//							iterateNode($val);
//						}
//					}
//					foreach ($node-> $sub as $temp) {//不能用foreach操作。因为foreach是拷贝操作。不会修改原来的数组
//						if(count($temp->children()) == 0){//没有子节点
//							@ $temp = replaceStr($temp); //会有warning提示。$node->$sub是数组类型。
//							echo $temp."<br />";
//						}else{
//							iterateNode($temp);
//						}
//					}
				} else {
					if(count($node->$sub->children()) == 0){
						@ $node->$sub = replaceStr($node->$sub); //会有warning提示。$node->$sub是数组类型。
					}else{
						iterateNode($node-> $sub); //遍历子节点
					}
				}
			}
		}
	}

}
//遍历属性 更改属性
function iterateAttr($node) {
	foreach ($node->attributes() as $attr => $val) {
		$newval = replaceStr($val);
		$node["$attr"] = $newval; //更改XML文件内容
	}
}

function readXml($path) {
	$xml = simplexml_load_file($path);
	$contentStacks = $xml->contentStacks; //一个版面
	iterateNode($contentStacks);
	$xml->asXML('Folio.xml'); //保存更改内容
}
?>
解析XML文件,处理xml文件中的空格 xml
<?php
$xmlArr = array ("Folio.xml");
readXml("Folio.xml");
function readXml($path){
	$dom = new DOMDocument();
	$dom->load($path);
	parseXml($dom->documentElement);
	$dom->save($path);//默认保存成unicode格式。中文会显示unicode
	file2utf8($path);
}
function parseXml($node) {
	$array = false;
	if ($node->hasAttributes()) { //有属性
		foreach ($node->attributes as $attr) {
			$attr->nodeValue = replaceStr($attr->nodeValue);
		}
	}
	if ($node->hasChildNodes()) { //有子节点
		if ($node->childNodes->length == 1) { //只有一个子节点
			parseXml($node->firstChild);
		} else {
			foreach ($node->childNodes as $childNode) {//遍历字节点
				if ($childNode->nodeType != XML_TEXT_NODE) {//不是文本节点
					parseXml($childNode);//递归
				}else{
					//echo $childNode->nodeType ;//Text
					//echo $childNode->nodeValue;
					//$childNode = replaceStr($childNode);
				}
			}
		}
	} else {//无字节点返回节点值
		$node->nodeValue = replaceStr($node->nodeValue);
	}
}
function replaceStr($str) {
	$newstr = str_replace(' ', '', trim($str)); //替换空格
	return $newstr;
}
//将所有内容都取出,转换成utf-8格式再保存回去
function file2utf8($filename) {
	$content = file_get_contents($filename);//读取文件内容
	$fp = fopen($filename, "w");//以写模式打开
//	$content = utf8_encode($content);
	$content = mb_convert_encoding($content, 'UTF-8', 'HTML-ENTITIES'); // 转换格式
	$content = "\xEF\xBB\xBF" . $content;
	fputs($fp, $content);
	fclose($fp);
}
?>
phonegap写文件和读文件 phonegap
<!DOCTYPE html>
<html>
  <head>
  <title></title>
  
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
	<meta charset="utf-8">
        
        <link type="text/css" href="style/style.css" rel="stylesheet"/>
        

	<!-- iPad/iPhone specific css below, add after your main css >
	<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="ipad.css" type="text/css" />		
	<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="iphone.css" type="text/css" />		
	-->
	<!-- If your application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->
	<script type="text/javascript" charset="utf-8" src="cordova-1.6.1.js"></script>
        
        <script type="text/javascript" src="scripts/jquery-1.7.2.min.js">
            </script>
    <script type="text/javascript">


	// If you want to prevent dragging, uncomment this section
	/*
	function preventBehavior(e) 
	{ 
      e.preventDefault(); 
    };
	document.addEventListener("touchmove", preventBehavior, false);
	*/
	
	/* If you are supporting your own protocol, the var invokeString will contain any arguments to the app launch.
	see http://iphonedevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
	for more details -jm */
	/*
	function handleOpenURL(url)
	{
		// TODO: do something with the url passed in.
	}
	*/
	
	function onBodyLoad()
	{		
		document.addEventListener("deviceready", onDeviceReady, false);
	}
	
	/* When this function is called, Cordova has been initialized and is ready to roll */
	/* If you are supporting your own protocol, the var invokeString will contain any arguments to the app launch.
	see http://iphonedevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
	for more details -jm */
	function onDeviceReady()
	{
		// do your thing!
		//navigator.notification.alert("Cordova is working")
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, readFile, fail);
        
	}
        
        function gotFS(fileSystem) {
            console.log(fileSystem.name);
            console.log(fileSystem.root.name);
            var parent = "download";
            fileSystem.root.getDirectory("myphonegap",{create: true, exclusive: false},function(directory){
                                         alert("directory has been created!");
                                         },fail);
            fileSystem.root.getFile("david.txt", {create: true, exclusive: false}, gotFileEntry, fail);
        }
        
        function gotFileEntry(fileEntry) {
            //fileEntry.createWriter(gotFileWriter, fail);
            fileEntry.file(function(file){
                var reader = new FileReader();
                    reader.onloadend = function(evt){
                    console.log("read success");
                    console.log("file data" + evt.target.result);
                }
                reader.readAsText(file);
                           },fail);
        }
        //读取文件
        function readFile(fileSystem){
            fileSystem.root.getFile("david.txt", {create: true, exclusive: false}, gotFileEntry, fail);

        }
        //创建文本并写入文件内容
        function gotFileWriter(writer) {
            writer.onwriteend = function(evt) {
                console.log("contents of file now 'some sample text'");
                writer.truncate(11);  
                writer.onwriteend = function(evt) {
                    console.log("contents of file now 'some sample'");
                    writer.seek(4);
                    writer.write(" different text");
                    writer.onwriteend = function(evt){
                        console.log("contents of file now 'some different text'");
                    }
                };
            };
            writer.write("some sample text");
        }
        
        function fail(error) {
            console.log(error.code);
        }
    
    </script>
  </head>
  <body onload="onBodyLoad()">
	<h1>Hey, it's Cordova!</h1>
	<p>Don't know how to get started? Check out our <em><a target="_blank" href="http://docs.phonegap.com/en/edge/guide_getting-started_ios_index.md.html#Getting%20Started%20with%20iOS">Getting Started Guide</a></em>
	<br />
	<ol>
		<li>Check your console log for any white-list rejection errors.</li>
		<li>Add your allowed <strong>hosts</strong> in Cordova.plist/ExternalHosts (wildcards OK, don't enter the URL scheme)</li>
	</ol>
    <a href="http://mobilea.nmg.com.hk">mobilea</a>
    <!--  <div id="tetris">
          <img src="offline/_MG_5925.JPG" class="offImg"><img src="offline/_MG_5926.JPG" class="offImg"><img src="offline/4463.jpg" class="offImg"><img src="offline/_DSC4833.jpg" class="offImg"><img src="offline/_DSC4603.JPG" class="offImg"><img src="offline/_DSC4617.JPG" class="offImg"><img src="offline/_DSC4635.JPG" class="offImg"><img src="offline/_DSC4667.JPG" class="offImg"><img src="offline/_DSC4829.JPG" class="offImg"><img src="offline/_DSC4831.JPG" class="offImg">
      </div>--><!-- Put your Markup Here -->
  </body>
</html>
eclipse插件地址 eclipse
導入eclipse可以用。包括aptano,php,android,gdata,
<?xml version="1.0" encoding="UTF-8"?>
<bookmarks>
   <site url="jar:file:/E:/android/android3.0-sdk/ADT-10.0.0.zip!/" selected="true" name="ADT"/>
   <site url="http://download.aptana.com/tools/studio/plugin/install/studio" selected="true" name="Aptana"/>
   <site url="http://download.aptana.org/tools/studio/plugin/install/frameworks/" selected="true" name="Aptana AJAX Frameworks Update Site"/>
   <site url="http://download.aptana.com/tools/radrails/plugin/install/radrails-studio/" selected="true" name="Aptana RadRails Update Site"/>
   <site url="http://download.aptana.org/tools/studio/plugin/install/xul" selected="true" name="Aptana XUL Update Site"/>
   <site url="http://download.eclipse.org/technology/babel/babel_language_packs/R0.9.0/helios" selected="true" name="babel"/>
   <site url="http://download.eclipse.org/technology/babel/update-site/R0.8.1/helios1" selected="true" name="babel"/>
   <site url="jar:file:/E:/work/g4j/API/com.google.gdata.feature_1.0.0.jar" selected="true" name="Google Data Api"/>
   <site url="jar:file:/E:/work/g4j/API/com.google.gdata.feature_1.0.0.jar!/" selected="true" name="Google Data Plugin"/>
   <site url="http://gdata-java-client-eclipse-plugin.googlecode.com/svn/update-site" selected="true" name="Google Data Plugin remote"/>
   <site url="http://dl.google.com/eclipse/plugin/beta/3.6" selected="true" name="Google Plugin"/>
   <site url="http://dl.google.com/eclipse/plugin/beta/3.7" selected="true" name="Google Plugin"/>
   <site url="http://download.eclipse.org/releases/helios" selected="true" name="Helios"/>
   <site url="http://www.langtags.com/jquerywtp/" selected="true" name="jQueryWTP"/>
   <site url="http://download.macromedia.com/pub/labs/jseclipse/autoinstall" selected="true" name="jsEclipse"/>
   <site url="http://download.aptana.org/tools/studio/plugin/install/xul-eclipse" selected="true" name="Mozilla XUL Update Site"/>
   <site url="http://download.eclipse.org/tools/mylyn/update/helios" selected="true" name="Mylyn for Eclipse Helios"/>
   <site url="http://phpeclipse.sourceforge.net/update/cvs" selected="true" name="php"/>
   <site url="http://phpeclipse.sourceforge.net/update/releases" selected="true" name="php2"/>
   <site url="http://www.spket.com/update/" selected="true" name="Spket"/>
   <site url="http://download.eclipse.org/eclipse/updates/3.6" selected="true" name="The Eclipse Project Updates"/>
   <site url="http://download.eclipse.org/webtools/repository/helios" selected="true" name="The Eclipse Web Tools Platform (WTP) software repository"/>
   <site url="file:/E:/android/android-sdk/android3.2/ADT-12.0.0/" selected="true" name="update site: file:/E:/android/android-sdk/android3.2/ADT-12.0.0/"/>
</bookmarks>
php调试技巧 php
//写入记录
$data = var_export($query,TRUE);
file_put_contents("data.txt",$data,FILE_APPEND);

PHP调试技巧。将变量的值写入文本文件。
Global site tag (gtag.js) - Google Analytics