PHP生成RSS订阅的程序代码
rss(简易信息聚合也叫聚合内容)是一种描述和同步网站内容的格式。下面的生成RSS订阅的代码:
rss XML结构
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title>网站名称</title> <link>http://www.111cn.net/</link> <description>网站描述!</description> <item> <title>RSS Tutorial</title> <link>网站地址/rss</link> <description>New RSS tutorial on W3School</description> </item> <item> <title>XML Tutorial</title> <link>网站地址/xml</link> <description>New XML tutorial on W3School</description> </item> </channel> </rss>
RSS实例
<?php class Rss { public function createFeed() { //RSS头部 $webUrl = 'http://'.$_SERVER['HTTP_HOST'];//网站地址 $webName = '网站名称'; //网站名称 $webDesc = '网站描述'; //网站描述 $html = '<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title>'.$webName.'</title> <link>'.$webUrl.'</link> <description>'.$webDesc.'</description> '.$this->createItem().' </channel> </rss> '; echo $html; } private function createItem() { //RSS item //$data可替换为自己的数据 $html = ''; //文章数据 $data = array( 'id' => 1, 'date' => date('r', time()), 'title' => '文章标题', 'link' => 'http://www.111cn.net', //文章地址 'description' => '网站描述' ); for($i = 0; $i < 6; $i++) { $html .= ' <item> <title>'.$data['title'].'</title> <link>'.$data['link'].'</link> <pubDate>'.$data['date'].'</pubDate> <description><![CDATA['.$data['description'].']]></description> </item> '; } return $html; } } header("Content-Type: text/xml; charset=utf-8"); $rss = new Rss(); $rss->createFeed(); exit; ?>
RSS Feed 生成后,如何设置才能给网站添加 RSS 呢?并且让 Firefox、IE7 或其它 Feed 机器人自动发现?很简单,在网页的 Head 节添加一个特定的 Link 标签即可,如下:
<link rel=”alternate” type=”application/rss+xml” title=”网站名称 RSS Feed” href=”http://www.111cn.net” />
设置 title 为 Feed 标题,href 为 Feed 地址,一切就 OK 了!
例子2
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0"> <channel> <title>php程序员教程网</title> <link>http://www.111cn.net/</link> <description>本站是一个php程序员的工作生活笔记!</description> <item> <title>RSS Tutorial</title> <link>网站地址/rss</link> <description>New RSS tutorial on W3School</description> </item> <item> <title>XML Tutorial</title> <link>网站地址/xml</link> <description>New XML tutorial on W3School</description> </item> </channel> </rss>
下面分享一段使用 php 动态生成 RSS 的代码示例:
<?php /** ** php 动态生成 RSS 类 **/ define("TIME_ZONE",""); define("FEEDCREATOR_VERSION","www.111cn.net");//您的网址 class FeedItem extends HtmlDescribable{ var $title,$description,$link; var $author,$authorEmail,$image,$category,$comments,$guid,$source,$creator; var $date; var $additionalElements=Array(); } class FeedImage extends HtmlDescribable{ var $title,$url,$link; var $width,$height,$description; } class HtmlDescribable{ var $descriptionHtmlSyndicated; var $descriptionTruncSize; function getDescription(){ $descriptionField=new FeedHtmlField($this->description); $descriptionField->syndicateHtml=$this->descriptionHtmlSyndicated; $descriptionField->truncSize=$this->descriptionTruncSize; return $descriptionField->output(); } } class FeedHtmlField{ var $rawFieldContent; var $truncSize,$syndicateHtml; function FeedHtmlField($parFieldContent){ if($parFieldContent){ $this->rawFieldContent=$parFieldContent; } } function output(){ if(!$this->rawFieldContent){ $result=""; } elseif($this->syndicateHtml){ $result="<![CDATA[".$this->rawFieldContent."]]>"; }else{ if($this->truncSize and is_int($this->truncSize)){ $result=FeedCreator::iTrunc(htmlspecialchars($this->rawFieldContent),$this->truncSize); }else{ $result=htmlspecialchars($this->rawFieldContent); } } return $result; } } class UniversalFeedCreator extends FeedCreator{ var $_feed; function _setFormat($format){ switch (strtoupper($format)){ case "2.0": // fall through case "RSS2.0": $this->_feed=new RSSCreator20(); break; case "0.91": // fall through case "RSS0.91": $this->_feed=new RSSCreator091(); break; default: $this->_feed=new RSSCreator091(); break; } $vars=get_object_vars($this); foreach ($vars as $key => $value){ // prevent overwriting of properties "contentType","encoding"; do not copy "_feed" itself if(!in_array($key, array("_feed","contentType","encoding"))){ $this->_feed->{$key}=$this->{$key}; } } } function createFeed($format="RSS0.91"){ $this->_setFormat($format); return $this->_feed->createFeed(); } function saveFeed($format="RSS0.91",$filename="",$displayContents=true){ $this->_setFormat($format); $this->_feed->saveFeed($filename,$displayContents); } function useCached($format="RSS0.91",$filename="",$timeout=3600){ $this->_setFormat($format); $this->_feed->useCached($filename,$timeout); } } class FeedCreator extends HtmlDescribable{ var $title,$description,$link; var $syndicationURL,$image,$language,$copyright,$pubDate,$lastBuildDate,$editor,$editorEmail,$webmaster,$category,$docs,$ttl,$rating,$skipHours,$skipDays; var $xslStyleSheet=""; var $items=Array(); var $contentType="application/xml"; var $encoding="utf-8"; var $additionalElements=Array(); function addItem($item){ $this->items[]=$item; } function clearItem2Null(){ $this->items=array(); } function iTrunc($string,$length){ if(strlen($string)<=$length){ return $string; } $pos=strrpos($string,"."); if($pos>=$length-4){ $string=substr($string,0,$length-4); $pos=strrpos($string,"."); } if($pos>=$length*0.4){ return substr($string,0,$pos+1)." ..."; } $pos=strrpos($string," "); if($pos>=$length-4){ $string=substr($string,0,$length-4); $pos=strrpos($string," "); } if($pos>=$length*0.4){ return substr($string,0,$pos)." ..."; } return substr($string,0,$length-4)." ..."; } function _createGeneratorComment(){ return "<!-- generator=\"".FEEDCREATOR_VERSION."\" -->\n"; } function _createAdditionalElements($elements,$indentString=""){ $ae=""; if(is_array($elements)){ foreach($elements AS $key => $value){ $ae.= $indentString."<$key>$value</$key>\n"; } } return $ae; } function _createStylesheetReferences(){ $xml=""; if($this->cssStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->cssStyleSheet."\" type=\"text/css\"?>\n"; if($this->xslStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->xslStyleSheet."\" type=\"text/xsl\"?>\n"; return $xml; } function createFeed(){} function _generateFilename(){ $fileInfo=pathinfo($_SERVER["PHP_SELF"]); return substr($fileInfo["basename"],0,-(strlen($fileInfo["extension"])+1)).".xml"; } function _redirect($filename){ Header("Content-Type: ".$this->contentType."; charset=".$this->encoding."; filename=".basename($filename)); Header("Content-Disposition: inline; filename=".basename($filename)); readfile($filename,"r"); die(); } function useCached($filename="",$timeout=3600){ $this->_timeout=$timeout; if($filename==""){ $filename=$this->_generateFilename(); } if(file_exists($filename) && (time()-filemtime($filename) < $timeout)){ $this->_redirect($filename); } } function saveFeed($filename="",$displayContents=true){ if($filename==""){ $filename=$this->_generateFilename(); } $feedFile=fopen($filename,"w+"); if($feedFile){ fputs($feedFile,$this->createFeed()); fclose($feedFile); if($displayContents){ $this->_redirect($filename); } }else{ echo "<br /><b>Error creating feed file, please check write permissions.</b><br />"; } } } class FeedDate{ var $unix; function FeedDate($dateString=""){ if($dateString=="") $dateString=date("r"); if(is_integer($dateString)){ $this->unix=$dateString; return; } if(preg_match("~(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s+)?(\\d{1,2})\\s+([a-zA-Z]{3})\\s+(\\d{4})\\s+(\\d{2}):(\\d{2}):(\\d{2})\\s+(.*)~",$dateString,$matches)){ $months=Array("Jan"=>1,"Feb"=>2,"Mar"=>3,"Apr"=>4,"May"=>5,"Jun"=>6,"Jul"=>7,"Aug"=>8,"Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12); $this->unix=mktime($matches[4],$matches[5],$matches[6],$months[$matches[2]],$matches[1],$matches[3]); if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){ $tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60; }else{ if(strlen($matches[7])==1){ $oneHour=3600; $ord=ord($matches[7]); if($ord < ord("M")){ $tzOffset=(ord("A") - $ord - 1) * $oneHour; } elseif($ord >= ord("M") && $matches[7]!="Z"){ $tzOffset=($ord - ord("M")) * $oneHour; } elseif($matches[7]=="Z"){ $tzOffset=0; } } switch ($matches[7]){ case "UT": case "GMT": $tzOffset=0; } } $this->unix += $tzOffset; return; } if(preg_match("~(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(.*)~",$dateString,$matches)){ $this->unix=mktime($matches[4],$matches[5],$matches[6],$matches[2],$matches[3],$matches[1]); if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){ $tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60; }else{ if($matches[7]=="Z"){ $tzOffset=0; } } $this->unix += $tzOffset; return; } $this->unix=0; } function rfc822(){ $date=gmdate("Y-m-d H:i:s",$this->unix); if(TIME_ZONE!="") $date .= " ".str_replace(":","",TIME_ZONE); return $date; } function iso8601(){ $date=gmdate("Y-m-d H:i:s",$this->unix); $date=substr($date,0,22) . ':' . substr($date,-2); if(TIME_ZONE!="") $date=str_replace("+00:00",TIME_ZONE,$date); return $date; } function unix(){ return $this->unix; } } class RSSCreator10 extends FeedCreator{ function createFeed(){ $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n"; $feed.= $this->_createGeneratorComment(); if($this->cssStyleSheet==""){ $cssStyleSheet="http://www.w3.org/2000/08/w3c-synd/style.css"; } $feed.= $this->_createStylesheetReferences(); $feed.= "<rdf:RDF\n"; $feed.= " xmlns=\"http://purl.org/rss/1.0/\"\n"; $feed.= " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"; $feed.= " xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n"; $feed.= " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"; $feed.= " <channel rdf:about=\"".$this->syndicationURL."\">\n"; $feed.= " <title>".htmlspecialchars($this->title)."</title>\n"; $feed.= " <description>".htmlspecialchars($this->description)."</description>\n"; $feed.= " <link>".$this->link."</link>\n"; if($this->image!=null){ $feed.= " <image rdf:resource=\"".$this->image->url."\" />\n"; } $now=new FeedDate(); $feed.= " <dc:date>".htmlspecialchars($now->iso8601())."</dc:date>\n"; $feed.= " <items>\n"; $feed.= " <rdf:Seq>\n"; for ($i=0;$i<count($this->items);$i++){ $feed.= " <rdf:li rdf:resource=\"".htmlspecialchars($this->items[$i]->link)."\"/>\n"; } $feed.= " </rdf:Seq>\n"; $feed.= " </items>\n"; $feed.= " </channel>\n"; if($this->image!=null){ $feed.= " <image rdf:about=\"".$this->image->url."\">\n"; $feed.= " <title>".$this->image->title."</title>\n"; $feed.= " <link>".$this->image->link."</link>\n"; $feed.= " <url>".$this->image->url."</url>\n"; $feed.= " </image>\n"; } $feed.= $this->_createAdditionalElements($this->additionalElements," "); for ($i=0;$i<count($this->items);$i++){ $feed.= " <item rdf:about=\"".htmlspecialchars($this->items[$i]->link)."\">\n"; //$feed.= " <dc:type>Posting</dc:type>\n"; $feed.= " <dc:format>text/html</dc:format>\n"; if($this->items[$i]->date!=null){ $itemDate=new FeedDate($this->items[$i]->date); $feed.= " <dc:date>".htmlspecialchars($itemDate->iso8601())."</dc:date>\n"; } if($this->items[$i]->source!=""){ $feed.= " <dc:source>".htmlspecialchars($this->items[$i]->source)."</dc:source>\n"; } if($this->items[$i]->author!=""){ $feed.= " <dc:creator>".htmlspecialchars($this->items[$i]->author)."</dc:creator>\n"; } $feed.= " <title>".htmlspecialchars(strip_tags(strtr($this->items[$i]->title,"\n\r"," ")))."</title>\n"; $feed.= " <link>".htmlspecialchars($this->items[$i]->link)."</link>\n"; $feed.= " <description>".htmlspecialchars($this->items[$i]->description)."</description>\n"; $feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements," "); $feed.= " </item>\n"; } $feed.= "</rdf:RDF>\n"; return $feed; } } class RSSCreator091 extends FeedCreator{ var $RSSVersion; function RSSCreator091(){ $this->_setRSSVersion("0.91"); $this->contentType="application/rss+xml"; } function _setRSSVersion($version){ $this->RSSVersion=$version; } function createFeed(){ $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n"; $feed.= $this->_createGeneratorComment(); $feed.= $this->_createStylesheetReferences(); $feed.= "<rss version=\"".$this->RSSVersion."\">\n"; $feed.= " <channel>\n"; $feed.= " <title>".FeedCreator::iTrunc(htmlspecialchars($this->title),100)."</title>\n"; $this->descriptionTruncSize=500; $feed.= " <description>".$this->getDescription()."</description>\n"; $feed.= " <link>".$this->link."</link>\n"; $now=new FeedDate(); $feed.= " <lastBuildDate>".htmlspecialchars($now->rfc822())."</lastBuildDate>\n"; $feed.= " <generator>".FEEDCREATOR_VERSION."</generator>\n"; if($this->image!=null){ $feed.= " <image>\n"; $feed.= " <url>".$this->image->url."</url>\n"; $feed.= " <title>".FeedCreator::iTrunc(htmlspecialchars($this->image->title),100)."</title>\n"; $feed.= " <link>".$this->image->link."</link>\n"; if($this->image->width!=""){ $feed.= " <width>".$this->image->width."</width>\n"; } if($this->image->height!=""){ $feed.= " <height>".$this->image->height."</height>\n"; } if($this->image->description!=""){ $feed.= " <description>".$this->image->getDescription()."</description>\n"; } $feed.= " </image>\n"; } if($this->language!=""){ $feed.= " <language>".$this->language."</language>\n"; } if($this->copyright!=""){ $feed.= " <copyright>".FeedCreator::iTrunc(htmlspecialchars($this->copyright),100)."</copyright>\n"; } if($this->editor!=""){ $feed.= " <managingEditor>".FeedCreator::iTrunc(htmlspecialchars($this->editor),100)."</managingEditor>\n"; } if($this->webmaster!=""){ $feed.= " <webMaster>".FeedCreator::iTrunc(htmlspecialchars($this->webmaster),100)."</webMaster>\n"; } if($this->pubDate!=""){ $pubDate=new FeedDate($this->pubDate); $feed.= " <pubDate>".htmlspecialchars($pubDate->rfc822())."</pubDate>\n"; } if($this->category!=""){ $feed.= " <category>".htmlspecialchars($this->category)."</category>\n"; } if($this->docs!=""){ $feed.= " <docs>".FeedCreator::iTrunc(htmlspecialchars($this->docs),500)."</docs>\n"; } if($this->ttl!=""){ $feed.= " <ttl>".htmlspecialchars($this->ttl)."</ttl>\n"; } if($this->rating!=""){ $feed.= " <rating>".FeedCreator::iTrunc(htmlspecialchars($this->rating),500)."</rating>\n"; } if($this->skipHours!=""){ $feed.= " <skipHours>".htmlspecialchars($this->skipHours)."</skipHours>\n"; } if($this->skipDays!=""){ $feed.= " <skipDays>".htmlspecialchars($this->skipDays)."</skipDays>\n"; } $feed.= $this->_createAdditionalElements($this->additionalElements," "); for ($i=0;$i<count($this->items);$i++){ $feed.= " <item>\n"; $feed.= " <title>".FeedCreator::iTrunc(htmlspecialchars(strip_tags($this->items[$i]->title)),100)."</title>\n"; $feed.= " <link>".htmlspecialchars($this->items[$i]->link)."</link>\n"; $feed.= " <description>".$this->items[$i]->getDescription()."</description>\n"; if($this->items[$i]->author!=""){ $feed.= " <author>".htmlspecialchars($this->items[$i]->author)."</author>\n"; } /* // on hold if($this->items[$i]->source!=""){ $feed.= " <source>".htmlspecialchars($this->items[$i]->source)."</source>\n"; } */ if($this->items[$i]->category!=""){ $feed.= " <category>".htmlspecialchars($this->items[$i]->category)."</category>\n"; } if($this->items[$i]->comments!=""){ $feed.= " <comments>".htmlspecialchars($this->items[$i]->comments)."</comments>\n"; } if($this->items[$i]->date!=""){ $itemDate=new FeedDate($this->items[$i]->date); $feed.= " <pubDate>".htmlspecialchars($itemDate->rfc822())."</pubDate>\n"; } if($this->items[$i]->guid!=""){ $feed.= " <guid>".htmlspecialchars($this->items[$i]->guid)."</guid>\n"; } $feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements," "); $feed.= " </item>\n"; } $feed.= " </channel>\n"; $feed.= "</rss>\n"; return $feed; } } class RSSCreator20 extends RSSCreator091{ function RSSCreator20(){ parent::_setRSSVersion("2.0"); } }
使用示例:
<?php header('Content-Type:text/html; charset=utf-8'); $db=mysql_connect('127.0.0.1','root','123456'); mysql_query("set names utf8"); mysql_select_db('dbname',$db); $brs=mysql_query('select * from article order by add_time desc limit 0,10',$db); $rss=new UniversalFeedCreator(); $rss->title="页面标题"; $rss->link="网址http://"; $rss->description="rss标题"; while($rowbrs=mysql_fetch_array($brs)){ $item=new FeedItem(); $item->title =$rowbrs['subject']; $item->link='http://www.111cn.net/'; $item->description =$rowbrs['description']; $rss->addItem($item); } mysql_close($db); $rss->saveFeed("RSS2.0","rss.xml");json_encode函数对于中文的操作不行同了,如果是uft8下还会碰到中文转成u590fu5a03u7684u8bf1u60d这种字符了,那么我们要如何输出成中文呢,下面来看看。
最近使用json_encode转换数组为json数据,储存在数据库里面,因为字段的长度个内容不确定,就只能使用这个方法了,但是使用json_decode解析为数组以后,却出现了类
似”u590fu5a03u7684u8bf1u60d14u5979u7684u6280u5de7″,通过查询百度,这应该是UCS-2编码的字符串,那么如何转换这个字符串呢?
其实在在php5.2以前的版本中做json_encode转换的时候的时候。中文会被unicode编码, php5.3加入了options参数, 5.4以后才加入JSON_UNESCAPED_UNICODE,这个参数,不需要做escape和unicode处理。 所以在5.4之前都需要对中文做个处理。
php5.4里面的处理
json_encode($str, JSON_UNESCAPED_UNICODE);
php5.4之前,有两种方法处理
方法一
function encode_json($str){ return preg_replace("/u([0-9a-f]+)/ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $code); }
在实际应用中有个问题,部分字符会掉,不止为何,如字符串:”日期11.2″会被变成”日期.2″。
方法二
function encode_json($str) { return urldecode(json_encode(url_encode($str))); } function url_encode($str) { if(is_array($str)) { foreach($str as $key=>$value) { $str[urlencode($key)] = url_encode($value); } } else { $str = urlencode($str); } return $str; }
本站使用的是虚拟主机,就没法修改php的版本了,所以就只能采用第一种方法了,不过方法确实还是有效果的。
方法三 function decodeUnicode($str){ return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function( '$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");' ), $str); }
gzip压缩可以帮助我们节省带宽了,它可以帮助我们把10K的文件压缩到3k大小了,这个比例是非常的高的了,下面来看Nginx 开启gzip压缩(图片,文件,css)的配置。
1、Vim打开Nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
2、找到如下一段,进行修改
gzip on; gzip_min_length 1k; gzip_buffers 4 16k; #gzip_http_version 1.0; gzip_comp_level 2; gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary off; gzip_disable "MSIE [1-6]\.";
3、解释一下
第1行:开启Gzip
第2行:不压缩临界值,大于1K的才压缩,一般不用改
第3行:buffer,就是,嗯,算了不解释了,不用改
第4行:用了反向代理的话,末端通信是HTTP/1.0,有需求的应该也不用看我这科普文了;有这句的话注释了就行了,默认是HTTP/1.1
第5行:压缩级别,1-10,数字越大压缩的越好,时间也越长,看心情随便改吧
第6行:进行压缩的文件类型,缺啥补啥就行了,JavaScript有两种写法,最好都写上吧,总有人抱怨js文件没有压缩,其实多写一种格式就行了
第7行:跟Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding",我不需要这玩意,自己对照情况看着办吧
第8行:IE6对Gzip不怎么友好,不给它Gzip了
4、:wq保存退出,重新加载Nginx
/usr/local/nginx/sbin/nginx -s reload
5、用curl测试Gzip是否成功开启
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.111cn.net/" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:13:09 GMT Content-Type: text/html; charset=UTF-8 Connection: keep-alive X-Powered-By: PHP/5.2.17p1 X-Pingback: http://www.slyar.com/blog/xmlrpc.php Content-Encoding: gzip
页面成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.ye111cn.nethemes/default/statics/css/lib.css" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:21:25 GMT Content-Type: text/css Last-Modified: Sun, 26 Aug 2012 15:17:07 GMT Connection: keep-alive Expires: Mon, 27 Aug 2012 06:21:25 GMT Cache-Control: max-age=43200 Content-Encoding: gzip
css文件成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" http://www.111cn.net /Themes/default/statics/js/jquery.min.js" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:21:38 GMT Content-Type: application/x-javascript Last-Modified: Thu, 12 Jul 2012 17:42:45 GMT Connection: keep-alive Expires: Mon, 27 Aug 2012 06:21:38 GMT Cache-Control: max-age=43200 Content-Encoding: gzip
js文件成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-content/uploads/2012/08/2012-08-23_203542.png" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:22:45 GMT Content-Type: image/png Last-Modified: Thu, 23 Aug 2012 13:50:53 GMT Connection: keep-alive Expires: Tue, 25 Sep 2012 18:22:45 GMT Cache-Control: max-age=2592000 Content-Encoding: gzip
图片成功压缩
curl -I -H "Accept-Encoding: gzip, deflate" "http://www.slyar.com/blog/wp-content/plugins/wp-multicollinks/wp-multicollinks.css" HTTP/1.1 200 OK Server: nginx/1.0.15 Date: Sun, 26 Aug 2012 18:23:27 GMT Content-Type: text/css Content-Length: 180 Last-Modified: Sat, 02 May 2009 08:46:15 GMT Connection: keep-alive Expires: Mon, 27 Aug 2012 06:23:27 GMT Cache-Control: max-age=43200 Accept-Ranges: bytes
最后来个不到1K的文件,由于我的阈值是1K,所以没压缩
微信公众号号在手机中通过api接口可以实现自定义分享内容了,下面我们来看这个接口的实现步骤。
一、准备阶段
公众号一个,微网站一个。
二、绑定域名
先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。
备注:登录后可在“开发者中心”查看对应的接口权限。
三、代码
<?php //curl获取请求文本内容 function get_curl_contents($url, $method ='GET', $data = array()) { if ($method == 'POST') { //使用crul模拟 $ch = curl_init(); //禁用https curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //允许请求以文件流的形式返回 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 30); curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); //执行发送 curl_close($ch); }else { if (ini_get('allow_fopen_url') == '1') { $result = file_get_contents($url); }else { //使用crul模拟 $ch = curl_init(); //允许请求以文件流的形式返回 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //禁用https curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); //执行发送 curl_close($ch); } } return $result; } //获取微信公从号access_token function wx_get_token() { $AppID = '1235464654';//AppID(应用ID) $AppSecret = '705641465sdfasdf456465a4sdf';//AppSecret(应用密钥) $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$AppID.'&secret='.$AppSecret; $res = get_curl_contents($url); $res = json_decode($res, true); //这里应该把access_token缓存起来,至于要怎么缓存就看各位了,有效期是7200s return $res['access_token']; } //获取微信公从号ticket function wx_get_jsapi_ticket() { $url = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", wx_get_token()); $res = get_curl_contents($url); $res = json_decode($res, true); //这里应该把access_token缓存起来,至于要怎么缓存就看各位了,有效期是7200s return $res['ticket']; } $wx = array(); //生成签名的时间戳 $wx['timestamp'] = time(); //生成签名的随机串 $wx['noncestr'] = 'Wm3WZYTPz0wzccnW'; //jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。 $wx['jsapi_ticket'] = wx_get_jsapi_ticket(); //分享的地址,注意:这里是指当前网页的URL,不包含#及其后面部分,曾经的我就在这里被坑了,所以小伙伴们要小心了 $wx['url'] = 'http://www.baidu.com'; $string = sprintf("jsapi_ticket=%s&noncestr=%s×tamp=%s&url=%s", $wx['jsapi_ticket'], $wx['noncestr'], $wx['timestamp'], $wx['url']); //生成签名 $wx['signature'] = sha1($string); /* 注意事项 签名用的noncestr和timestamp必须与wx.config中的nonceStr和timestamp相同。 签名用的url必须是调用JS接口页面的完整URL。 出于安全考虑,开发者必须在服务器端实现签名的逻辑。 */ ?>
四、视图显示
在需要调用JS接口的页面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.js
通过config接口注入权限验证配置
<script> //通过config接口注入权限验证配置 wx.config({ debug : false, appId : 'AppID', timestamp : '<?php echo $wx["timestamp"];?>', nonceStr : '<?php echo $wx["noncestr"];?>', signature : '<?php echo $wx["signature"];?>', jsApiList : ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo'] }); wx.ready(function(){ var s_title = '分享标题', // 分享标题 s_link = '分享链接', // 分享链接 s_desc = '分享描述', //分享描述 s_imgUrl = '分享图片'; // 分享图标 //朋友圈 wx.onMenuShareTimeline({ title: s_title, // 分享标题 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 success: function () { }, cancel: function () { } }); //发送给好友 wx.onMenuShareAppMessage({ title: s_title, // 分享标题 desc: s_desc, // 分享描述 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 type: '', // 分享类型,music、video或link,不填默认为link dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空 success: function () {}, cancel: function () {} }); //QQ好友 wx.onMenuShareQQ({ title: s_title, // 分享标题 desc: s_desc, // 分享描述 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 success: function () { }, cancel: function () { } }); //腾讯微博 wx.onMenuShareWeibo({ title: s_title, // 分享标题 desc: s_desc, // 分享描述 link: s_link, // 分享链接 imgUrl: s_imgUrl, // 分享图标 success: function () { }, cancel: function () { } }); }); </script>
五、大功告成
基本上的流程就是这样了,比较麻烦的一点就是生成签名那一块,注意一点就行了
本文章来为各位介绍一篇关于php-fpm设置socket方式连接FastCGI的例子,希望文章可能帮助到各位深入的理解socket方式连接FastCGI的知识。socket方式不会走到tcp层,tcp方式则会走到ip层。因此,理论上说socket连接方式效率会更好一点。
TCP和unix domain socket方式对比
TCP是使用TCP端口连接127.0.0.1:9000
Socket是使用unix domain socket连接套接字/dev/shm/php-fpm.sock
修改php-fpm.conf配置
#listen = 127.0.0.1:9000 listen=/dev/shm/php-fpm.sock #/dev/shm/为内存文件系统,注意 确保可读写 listen.owner=apache #注意自己的用户和组 listen.group=apache
修改nginx.conf配置
#fastcgi_pass 127.0.0.1:9000; #将相应的如上内容修改如下 fastcgi_pass unix:/dev/shm/php-fpm.sock;
重启nginx和php-fpm
service nginx restart /usr/local/nginx/sbin/nginx -s reload
相关文章
- 这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
- 本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
- 有一种方法,可以不打开网站而直接查看到这个网站的源代码.. 这样可以有效地防止误入恶意网站... 在浏览器地址栏输入: view-source:http://...2016-09-20
- <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
- 本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
- 本文通过两个示例讲解了一下Process类调用外部应用程序的基本用法,并简单讲解了StartInfo属性,有需要的朋友可以参考一下。...2020-06-25
- 这篇文章主要介绍了微信小程序 页面传值详解的相关资料,需要的朋友可以参考下...2017-03-13
- 本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
- 本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
- php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
- php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p> </p> <p> </p> <form name="form1...2016-11-25
- 公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
- 大概有如下步骤 新建项目Bejs 新建文件package.json 新建文件Gruntfile.js 命令行执行grunt任务 一、新建项目Bejs源码放在src下,该目录有两个js文件,selector.js和ajax.js。编译后代码放在dest,这个grunt会...2014-06-07
- 本文实例讲述了JS实现双击屏幕滚动效果代码。分享给大家供大家参考,具体如下:这里演示双击滚屏效果代码的实现方法,不知道有觉得有用处的没,现在网上还有很多还在用这个特效的呢,代码分享给大家吧。运行效果截图如下:在线演...2015-10-30
- 其实挺简单的就是if(navigator.userAgent.indexOf('UCBrowser') > -1) {alert("uc浏览器");}else{//不是uc浏览器执行的操作}如果想测试某个浏览器的特征可以通过如下方法获取JS获取浏览器信息 浏览器代码名称:navigator...2015-11-08
- 一、日期减去天数等于第二个日期function cc(dd,dadd){//可以加上错误处理var a = new Date(dd)a = a.valueOf()a = a - dadd * 24 * 60 * 60 * 1000a = new Date(a)alert(a.getFullYear() + "年" + (a.getMonth() +...2015-11-08
- 这篇文章主要介绍了uniapp微信小程序:key失效的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-20
- 微信支付,即便交了保证金,你还是处理测试阶段,不能正式发布。必须到你通过程序测试提交订单、发货通知等数据到微信的系统中,才能申请发布。然后,因为在微信中是通过JS方式调用API,必须在微信后台设置支付授权目录,而且要到...2014-05-31
- 本文介绍两种使用 php 生成二维码的方法。 (1)利用google生成二维码的开放接口,代码如下: /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @param strin...2015-10-21
- 这篇文章主要介绍了Java生成随机姓名、性别和年龄的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-10-01