解决PHP的json_encode处理中文被转码为全英文的方法

 更新时间:2016年11月25日 15:34  点击:1654
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);
}

 

DIRECTORY_SEPARATOR在php中我们最常见的就是cms系统中的全局变量了,下面我们一起来看一个PHP预定义常量DIRECTORY_SEPARATOR的使用例子,具体如下所示。

DIRECTORY_SEPARATOR是一个显示系统分隔符的命令,DIRECTORY_SEPARATOR是PHP的内部常量,不需要任何定义与包含即可直接使用。

众所周知,在windows下路径分隔符是(当然/在部分系统上也是可以正常运行的),在linux上路径的分隔符是/,这就导致了一个问题,比如开发机器是windows,有一个图片上传程序,调试机器上指定的上传文件保存目录是:define(‘ROOT’, dirname(__FILE__).”upload”),在本地调试都很正常,但是上传到linux服务器的时候会发现会出错。

这个问题就是出在文件的分隔符上,windows上习惯性的使用作为文件分隔符,但是在linux上人家是不认识这个标识的,人家只认识/,于是就要引入下面这个php内置变量了:DIRECTORY_SEPARATOR。
上面的写法可以改写为以下无错写法:

define(‘ROOT’, dirname(__FILE__).DIRECTORY_SEPARATOR.”upload”);

这样就可以确保不会出错了。
例如discuz里面是这样写的:define(‘S_ROOT’, dirname(__FILE__).DIRECTORY_SEPARATOR);
回到问题本身上,DIRECTORY_SEPARATOR是一个返回跟操作系统相关的路径分隔符的php内置命令,在windows上返回,而在linux或者类unix上返回/,就是这么个区别,通常在定义包含文件路径或者上传保存目录的时候会用到

define('ROOT', dirname(__FILE__)."\upload");

在本地调试都很正常,但是上传到linux服务器后就会出错。所以如上代码严谨的写法为:

define('ROOT', dirname(__FILE__).DIRECTORY_SEPARATOR."upload");

提示:可以用函数get_defined_constants()来获取所有PHP常量,例如:

print_r(get_defined_constants());//get_defined_constants()返回所有常量数组

生成RSS非常的简单只需要使用rss格式然后生成输出到浏览器就可以了,重点就是要告诉浏览器你是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");

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&timestamp=%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>

五、大功告成

基本上的流程就是这样了,比较麻烦的一点就是生成签名那一块,注意一点就行了

[!--infotagslink--]

相关文章

  • js URLdecode()与urlencode方法支持中文解码

    下面来介绍在js中来利用urlencode对中文编码与接受到数据后利用URLdecode()对编码进行解码,有需要学习的机友可参考参考。 代码如下 复制代码 ...2016-09-20
  • php中json_decode()和json_encode()用法与中文不显示解决办法

    本文章介绍了关于php中json_decode()和json_encode()用法与中文不显示解决办法,有需要的朋友可以参考一下下。 php中json_decode()和json_encode() 1.json_decode(...2016-11-25
  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • 关于Mysql中文乱码问题该如何解决(乱码问题完美解决方案)

    最近两天做项目总是被乱码问题困扰着,这不刚把mysql中文乱码问题解决了,下面小编把我的解决方案分享给大家,供大家参考,也方便以后自己查阅。首先:用show variables like “%colla%”;show varables like “%char%”;这两条...2015-11-24
  • C#读取中文文件出现乱码的解决方法

    这篇文章主要介绍了C#读取中文文件出现乱码的解决方法,涉及C#中文编码的操作技巧,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • Mysql在debian系统中不能插入中文的终极解决方案

    在debian环境下,彻底解决mysql无法插入和显示中文的问题Linux下Mysql插入中文显示乱码解决方案mysql -uroot -p 回车输入密码进入mysql查看状态如下:默认的是客户端和服务器都用了latin1,所以会乱码。解决方案:mysql>use...2013-10-04
  • linux mint 下mysql中文支持问题

    一.mysql默认不支持中文,它的server和db默认是latin1编码.所以我们要将其改变为utf-8编码,因为utf-8包含了地球上大部分语言的二进制编码 1.关闭mysql服务 sudo /etc/init.d/mysql stop 2.修改mysql配置文件 mysql配...2015-10-21
  • Windows服务器MySQL中文乱码的解决方法

    我们自己鼓捣mysql时,总免不了会遇到这个问题:插入中文字符出现乱码,虽然这是运维先给配好的环境,但是在自己机子上玩的时候咧,总得知道个一二吧,不然以后如何优雅的吹牛B。...2015-03-15
  • php怎么用拼音 简单的php中文转拼音的实现代码

    小编分享了一段简单的php中文转拼音的实现代码,代码简单易懂,适合初学php的同学参考学习。 代码如下 复制代码 <?phpfunction Pinyin($_String...2017-07-06
  • PHP json_encode() 函数详解及中文乱码问题

    在 php 中使用 json_encode() 内置函数(php > 5.2)可以使用得 php 中数据可以与其它语言很好的传递并且使用它。这个函数的功能是将数值转换成json数据存储格式。<&#63;php$arr = array ( 'Name'=>'希亚', 'Age'...2015-11-08
  • Java连接数据库oracle中文乱码解决方案

    这篇文章主要介绍了Java连接数据库oracle中文乱码解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-05-16
  • FlashFXP连接站点中文显示乱码解决办法

    FlashFXP是一款常用的服务器客户连接软件了,我们可以通过FlashFXP来上传或下载文件,但有一些朋友使用FlashFXP时碰到中文目录或文件名乱码问题,那么要如何来解决呢?具体就...2016-10-10
  • php中把unicode编码转化为中文

    小编在网上看到最多的就是汉字转换unicode编码了,今天我们看到一个反过来的操作就是把unicode转换成中文了,下面一起来看看 这两天帮别人开发微信平台好友板块,存...2016-11-25
  • php 判断是否是中文/英文/数字示例代码

    复制代码 代码如下: $str='asb天水市12'; if (preg_match("/^[/x7f-/xff]+$/", $str)){ echo '全部是汉字'; }else { echo '不全是汉字'; } /** PHP自带的判断是否是中文, eregi('[^/x00-/x7F]', $str ) //中文 ereg...2013-10-04
  • php json_encode值中大括号与花括号区别

    1.当array是一个从0开始的连续数组时,json_encode出来的结果是一个由[]括起来的字符串而当array是不从0开始或者不连续的数组时,json_encode出来的结果是一个由{}括起来的key-value模式的字符串复制代码 代码如下:$test...2013-10-04
  • php中文转换成拼音代码

    <?php教程 function cn2pinyin($_string, $_code='gb2312') { $_datakey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|b...2016-11-25
  • JavaScript过滤字符串中的中文与空格方法汇总

    这篇文章主要介绍了JavaScript过滤字符串中的中文与空格方法汇总 的相关资料,需要的朋友可以参考下...2016-03-09
  • three.js显示中文字体与tween应用详析

    这篇文章主要给大家介绍了关于three.js显示中文字体与tween应用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-04
  • php 根据啊拉伯数字转变成大写中文数字

    // 原是是根据用户输入的数字判断再转换成想要的大写数字,如果我们先把大小写存在一个数组,再判断进行转换就OK了。 $data = $_POST['rmb']; if (!ereg("^[0-9.]",$dat...2016-11-25
  • PHP把16进制的编码转为中文程序代码

    今天在做公司的项目的时候,遇到一个问题,群聊天记录存入数据库的时候把聊天记录及央视使用16进制转换,我在做将聊天记录导出为text文本的时候,需要将聊天记录先从16进制转...2016-11-25