PHP预定义常量DIRECTORY_SEPARATOR详解

 更新时间:2016年11月25日 15:34  点击:2129
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()返回所有常量数组

OPcache 通过将 PHP 脚本预编译的字节码存储到共享内存中来提升 PHP 的性能, 存储预编译字节码的好处就是 省去了每次加载和解析 PHP 脚本的开销。PHP 5.5.0 及后续版本中已经绑定了 OPcache 扩展,下面我们来看opcache PHP新的字节码缓存扩展详解

字节码缓存组件 Zend Optimizer+ 现在更改名字为 Zend opcache了。且在php 5.5版本后,会集成到php的官方组件中,也就没有必要安装其他的APC,eAccelerator等了。。

APC与Opcache都是字节码缓存也就是,PHP在被编译的时候,首先会把php代码转换为字节码,字节码然后被执行。

php文件第二次执行时,同样还是会重新转换为字节码,但是很多时候,文件内容几乎是一样的,比如静态HTML文件,生成后内容许久都不会改变,用户访问请求直接由服务器读取响应给客户端浏览器。都不用经过PHP进行解析构建了。

内存中的字节码数据,可以直接缓存进行二次编译。这样程序就会快一些,cpu的消耗也少了。

详细介绍看这两篇

新一代 PHP 加速插件 Zend Opcache

php的 zend opcache VS apc 性能比较

我主要是用来测试了一下phpcmsV9.5.4 的默认index.php主页,没有数据内容,但有sql查询操作

测试是Apache2.2.6 32Bit 服务器,PHP 5.4.26 ts,mysql 5.6.16 64Bit

ab 版本 This is ApacheBench, Version 2.3 <$Revision: 655654 $>

请求数:1000

并发数:10

没有加载opcache测试

第一次测试


p

吞吐率 38.46 rps,耗时26.001 s,每个请求耗时260.015 ms
第二次测试

p2

吞吐率有所提高 40.73 rps,耗时 24.554 s,每个请求耗时245.544 ms

加载opcache进行测试
opcache版本 php_opcache-7.0.3-5.4-ts-vc9-x86

opcache配置信息

 

1 opcache.memory_consumption=128
2 opcache.interned_strings_buffer=8
3 opcache.max_accelerated_files=4000
4 opcache.revalidate_freq=60
5 opcache.fast_shutdown=1
6 opcache.enable_cli=1
 
第一次配置opcache好后 cache 状态
cstat
 
cache hits 命中数 1
cache misses 未命中数 1
使用内存225.2Kb
opcache第一次测试
p_c1
吞吐率提升到49.11rps,总耗时20.361 s,每个请求耗时下降到203.612 ms
在phpinfo中可查看opcache的命中数量情况
cstat_c
命中数量已达到43957,内存使用2.31Mb。
opcache第二次测试
p_c2
吞吐率提升到47.87rps,总耗时20.888 s,每个请求耗时下降到208.882 ms
opcache之后的两次压测数据变化不大,每个请求耗时在1ms差距内,吞吐率也在1~2 rps
但与之前未启用opcache时,总耗时少了4 ~ 6 s,每个请求耗时少了40 ~ 60 ms。吞吐率也提升了 8%。
这都是在一行代码未改的情况下有效性能提升。
 
php文件被编译为字节码进行内存缓存,如果在生成环境中,代码和内容变量都是比较固定的
缓存起来的内容就可以高速的返回,用户会得到较快的响应。
但是在本地开发是,建议不要开启opcache,否则就得不到最新的值

例如:

<?php
 header('Content-type:text/html; charset=utf-8');
 
 $str = 'abc';
 echo $str; // 输出abc
?>


赋予$str 一个新的值

<?php
 header('Content-type:text/html; charset=utf-8');
 
 $str = 'new abc';
 echo $str; // 输出的还是 abc
?>

这是因为$str 已经被编译为字节码了,再次访问时,内存里面还是可以找到对应的缓存,就没有进行重新编译,返回的值也就还是之前的值 abc

不过,opcache有一个参数可以用来设置缓存时间长度


opcache.force_restart_timeout (default "180")

默认时间为180秒,还是建议本地不用开启opcache

 

注意:官方给了一个Note,如果opcache要与xdebug同时加载,那么opcache需要在xdebug之前进行加载。

但是我本地测试了一下,xdebug先加载,再加载opcache,也正常启动了,xdebug,opcache都加载成功,opcache缓存也正常。

不过还是按照官方的建议来安装加载,否则可能会出现奇怪的错误吧

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);
}

 

生成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,所以没压缩

[!--infotagslink--]

相关文章

  • 解决:failed to open stream: No such file or directory in

    本教程来给各位同学介绍failed to open stream: No such file or directory in解决办法,有需要了解的朋友可进入参考。 Warning: include_once(./include/main.i...2016-11-25
  • 在IDEA使用中directory和package的操作

    这篇文章主要介绍了在IDEA使用中directory和package的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-13
  • WIN2008 R2 Active Directory 之二 部署企业中Windows Server 2008 R2额外域控制器

    通过部署企业中第一台Windows Server 2008 R2域控制器已经完成了企业中Windows网络域森林的建立。但是,在企业中对于AD来讲,为了保证安全稳定运行,至少需要两台以上的物理域控制器...2016-01-27
  • Ubuntu上的android sdk提示 ./emulator: No such file or directory如何解决

    在64位的Ubuntu上运行android sdk遇到“-bash: ./emulator: No such file or directory”的错误提示,发现是64位的Ubuntu系统上刚好缺少所依赖的32位的库。 前几...2016-09-20
  • PHP预定义常量DIRECTORY_SEPARATOR详解

    DIRECTORY_SEPARATOR在php中我们最常见的就是cms系统中的全局变量了,下面我们一起来看一个PHP预定义常量DIRECTORY_SEPARATOR的使用例子,具体如下所示。 DIRECTORY_...2016-11-25
  • mysql_connect提示"No such file or directory"错误"

    有些朋友在使用mysql连接时会出现No such file or directory错误提示,下面我来总结解决办法。 连接代码 代码如下 复制代码 $this->linkid =...2016-11-25
  • php 预定义变量各种方法总结

    PHP 提供了大量的预定义变量。由于许多变量依赖于运行的服务器的版本和设置,及其它因素,所以并没有详细的说明文档。一些预定义变量在 PHP 以命令行形式运行时并不生效...2016-11-25
  • php html过滤代码(预定义的字符转换为 HTML 实体)

    //把一些预定义的字符转换为 HTML 实体 以及在预定义字符前加上反斜杠,包括 单引号、双引号、反斜杠、NULL,以保护数据库安全 function d_htmlspecialchars($strin...2016-11-25
  • c# DataDirectory的用法

    这篇文章主要介绍了c# DataDirectory的用法,帮助大家更好的理解和学习c#,感兴趣的朋友可以了解下...2020-11-03
  • PHP的DIRECTORY_SEPARATOR,PATH_SEPARATOR

    PHP的DIRECTORY_SEPARATOR,PATH_SEPARATOR 有需要的朋友可参考。 DIRECTORY_SEPARATOR:路径分隔符,linux上就是&lsquo;/&rsquo; windows上是&lsquo;&rsquo; 一个...2016-11-25
  • mysql_connect提示"No such file or directory"错误"

    有些朋友在使用mysql连接时会出现No such file or directory错误提示,下面我来总结解决办法。 连接代码 代码如下 复制代码 $this->linkid =...2016-11-25
  • 我想找出所有的预定义的数值,但为何所有文件都没

    最好的方法是建立一个新的页面,使用<?phpinfo()?>,并在浏览器中载入。它会显示所有的PHP参数信息、环境变量、WEB服务器的特定变量、HTTP的相关变量...等等。没有将完整...2016-11-25
  • php中常量DIRECTORY_SEPARATOR深入分析

    DIRECTORY_SEPARATOR在php是什么意思呢,在什么时候使用DIRECTORY_SEPARATOR最合理呢?下面来给各位介绍一下php DIRECTORY_SEPARATOR常量。 我们知道DIRECTORY_SEPAR...2016-11-25
  • Directory文件类的实例讲解

    下面小编就为大家分享一篇Directory文件类的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-06-25
  • Path类与Directory类与File类对路径/目录/文件的操作实例

    本文将详细介绍下:Path对路径字符串进行操作/Directory和DirectoryInfo 对目录进行操作/File和FileInfo对文件进行操作,感兴趣的你可不要错过了哈...2021-09-22
  • 预定义变量

    务器变量:$_SERVER 注: 在 PHP 4.1.0 及以后版本使用。之前的版本,使用 $HTTP_SERVER_VARS。 $_SERVER 是一个包含诸如头部(headers)、路径(paths)和脚本位置(script...2016-11-25
  • mysql_connect提示"No such file or directory"错误"

    有些朋友在使用mysql连接时会出现No such file or directory错误提示,下面我来总结解决办法。 连接代码 代码如下 复制代码 $this->linkid =...2016-09-20
  • Yii2.0预定义的别名功能小结

    这篇文章主要介绍了Yii2.0预定义的别名功能,总结分析了Yii2.0常见的12个预定义别名的具体表示方法与对应功能,需要的朋友可以参考下...2016-07-25
  • PHP预定义接口使用学习笔记

    我们知道php提供了6个迭代器接口了,那么这6个接口怎么样呢?有没有朋友都了解?如果各位朋友不知道的可以和小编一起来看看. PHP预定义了6个接口介绍如下: ...2016-11-25
  • PHP LDAP 访问 Windows AD(Active Directory)

    如果使用活动目录(Active Directory)代替在数据库表中建立账号, 你可以使用原来Windows网络中的账号. LDAP, 轻量级目录访问协议(Lightweight Directory...2016-11-25