分类归档: PHP

NGINX userid 分析、解码

生成userid的代码在 http/modules/ngx_http_userid_filter_module.c 大概550行左右。
uid_set 是4个uint32构成的,其中比较有用的是第二个unit32,是userid的生成时间。第四个是一个递增值 以 0x03030302 为初始值,每次递增0x100。

default: /* AF_INET */
                sin = (struct sockaddr_in *) c->local_sockaddr;
                ctx->uid_set[0] = sin->sin_addr.s_addr;
                break;
            }

        } else {
            ctx->uid_set[0] = htonl(conf->service);
        }

        ctx->uid_set[1] = htonl((uint32_t) ngx_time());
        ctx->uid_set[2] = htonl(start_value);
        ctx->uid_set[3] = htonl(sequencer_v2);
        sequencer_v2 += 0x100;
        if (sequencer_v2 < 0x03030302) {
            sequencer_v2 = 0x03030302;
        }
// 用PHP解码nginx userid
$str = $_REQUEST["uid"] ?: $_COOKIE['uid'];

function nginx_userid_decode($str)
{
        return  unpack('N*', base64_decode(str_replace(' ', '+', $str)));
}

$hash = nginx_userid_decode($str);
var_dump($hash);
date_default_timezone_set("UTC");
var_dump(date("Y-m-d H:i:s", $hash[2]));

参考文章:
http://www.lsproc.com/blog/nginx_userid_decode/

从百度空间导入到WordPress

从此这里做主博了,于是写了个导入程序把我百度空间的东西也搬了过来,下次还得写个导入相册的。。。

看了网上很多导入工具都是用的RSS来导入,会丢掉很多东西,而且一些被百度和谐掉的内容是抓取不到的,所以做了这么个工具通过采集的方式直接从HTML里抓取博客内容。

 

源文件下载:import_baiduhi.php_.zip

 

配置方法:

在程序底部修改下面两个变量的值,如果不想抓私密文章cookie留空也可以。

$account = 'meshikar'; //百度空间的URL后缀
$cookie = 'YOUR COOKIE'; //登陆后的百度COOKIE,用于抓取私密文章

附上Cookie的获取方法:

登陆后用firefox的firebug在网络选项卡中点开第一个请求,查看请求头信息把Cookie的内容复制下来就是了。

cookie的获取方法

使用方法:

把文件放到 /wordpress/scripts 目录下,在命令行用PHP CLI运行。

当然也可以通过HTTP执行,只要你执行时间限制足够你导入。

[转]php sphinx 高效率搜索引擎搭建

原文地址:http://blog.csdn.net/adparking/article/details/7207119

 

1.下载PHP客户端安装:

http://pecl.php.net/package/sphinx

 

vim sphinxclient.c
找到
void sock_close ( int sock );
改为
static void sock_close ( int sock );

 


 在php.ini加扩展,客户端安装完毕 2.安装sphinx,前提你已经安装mysql且安装了mysql-devel重源码安装mysql的

mysql-devel都已经安装,yum安装的运行
yum -y install mysql-devel

下载sphinx2.0.1地址:  

http://sphinxsearch.com/downloads/

 

tar -xvzf sphinx-2.0.1-beta.tar.gz
cd sphinx-2.0.1-beta
./configure –prefix=/usr/local/sphinx –with-mysql –with-iconv

 

备注:64位增加参数 –enable-id64


make && make install cd /usr/local/sphinx/etc/ cp sphinx.conf.dist sphinx.conf

 

[plain] view plaincopy

 

 

 

    1. #  

 

  • # Sphinx configuration file sample  

 

 

  • #  

 

 

  • # WARNING! While this sample file mentions all available options,  

 

 

  • # it contains (very) short helper descriptions only. Please refer to  

 

 

  • # doc/sphinx.html for details.  

 

 

  • #  

 

 

  •   

 

 

  • #############################################################################  

 

 

  • ## data source definition  

 

 

  • #############################################################################  

 

 

  •   

 

 

  • source src1  

 

 

  • {  

 

 

  •     # data source type. mandatory, no default value  

 

 

  •     # known types are mysql, pgsql, mssql, xmlpipe, xmlpipe2, odbc  

 

 

  •     type            = mysql  

 

 

  •   

 

 

  •     #####################################################################  

 

 

  •     ## SQL settings (for ‘mysql’ and ‘pgsql’ types)  

 

 

  •     #####################################################################  

 

 

  •   

 

 

  •     # some straightforward parameters for SQL source types  

 

 

  •     sql_host        = localhost  

 

 

  •     sql_user        = root  

 

 

  •     sql_pass        = ******   

 

 

  •     sql_db            = ******  

 

 

  •     sql_port        = 3306    # optional, default is 3306  

 

 

  •   

 

 

  •     # UNIX socket name  

 

 

  •     # optional, default is empty (reuse client library defaults)  

 

 

  •     # usually ‘/var/lib/mysql/mysql.sock’ on Linux  

 

 

  •     # usually ‘/tmp/mysql.sock’ on FreeBSD  

 

 

  •     #  

 

 

  •     sql_sock        = /tmp/mysql.sock  

 

 

  •   

 

 

  •   

 

 

  •     # MySQL specific client connection flags  

 

 

  •     # optional, default is 0  

 

 

  •     # 数据传输方式  

 

 

  •     # mysql_connect_flags    = 32 # enable compression  

 

 

  •   

 

 

  •     # MySQL specific SSL certificate settings  

 

 

  •     # optional, defaults are empty  

 

 

  •     # SLL链接  

 

 

  •     # mysql_ssl_cert        = /etc/ssl/client-cert.pem  

 

 

  •     # mysql_ssl_key        = /etc/ssl/client-key.pem  

 

 

  •     # mysql_ssl_ca        = /etc/ssl/cacert.pem  

 

 

  •   

 

 

  •     # MS SQL specific Windows authentication mode flag  

 

 

  •     # MUST be in sync with charset_type index-level setting  

 

 

  •     # optional, default is 0  

 

 

  •     #  

 

 

  •     # mssql_winauth        = 1 # use currently logged on user credentials  

 

 

  •   

 

 

  •   

 

 

  •     # MS SQL specific Unicode indexing flag  

 

 

  •     # optional, default is 0 (request SBCS data)  

 

 

  •     #  

 

 

  •     # mssql_unicode        = 1 # request Unicode data from server  

 

 

  •   

 

 

  •   

 

 

  •     # ODBC specific DSN (data source name)  

 

 

  •     # mandatory for odbc source type, no default value  

 

 

  •     #  

 

 

  •     # odbc_dsn        = DBQ=C:\data;DefaultDir=C:\data;Driver={Microsoft Text Driver (*.txt; *.csv)};  

 

 

  •     # sql_query        = SELECT id, data FROM documents.csv  

 

 

  •   

 

 

  •   

 

 

  •     # ODBC and MS SQL specific, per-column buffer sizes  

 

 

  •     # optional, default is auto-detect  

 

 

  •     #  

 

 

  •     # sql_column_buffers    = content=12M, comments=1M  

 

 

  •   

 

 

  •   

 

 

  •     # pre-query, executed before the main fetch query  

 

 

  •     # multi-value, optional, default is empty list of queries  

 

 

  •     # 发送SQL语句前发送  

 

 

  •     sql_query_pre        = SET NAMES utf8  

 

 

  •     sql_query_pre        = SET SESSION query_cache_type=OFF  

 

 

  •   

 

 

  •   

 

 

  •     # main document fetch query  

 

 

  •     # mandatory, integer document ID field MUST be the first selected column  

 

 

  •     # 需要查询的表 构建查询  

 

 

  •     sql_query        = \  

 

 

  •         SELECT id,target_type,genre,stars,sub_title,sports_team,music_band,music_album \  

 

 

  •         FROM ko_link  

 

 

  • #如果多个数据源并要在一个索引,必须要保持字段的顺序数量跟数据都要一致,否则将出错  

 

 

  •   

 

 

  •   

 

 

  •     # joined/payload field fetch query  

 

 

  •     # joined fields let you avoid (slow) JOIN and GROUP_CONCAT  

 

 

  •     # payload fields let you attach custom per-keyword values (eg. for ranking)  

 

 

  •     #  

 

 

  •     # syntax is FIELD-NAME ‘from’  ( ‘query’ | ‘payload-query’ ); QUERY  

 

 

  •     # joined field QUERY should return 2 columns (docid, text)  

 

 

  •     # payload field QUERY should return 3 columns (docid, keyword, weight)  

 

 

  •     #  

 

 

  •     # REQUIRES that query results are in ascending docuent ID order!  

 

 

  •     # multi-value, optional, default is empty list of queries  

 

 

  •     #  添加字段,来源与表 自动连接  

 

 

  • # 字段结果集保持为  

 

 

  • # (1,tags1)  

 

 

  • # (1,tags2)  

 

 

  • # (2,tags3)  

 

 

  • # (2,tags4)  

 

 

  • # 添加字段将用于搜索,结果如有第3个字段,第3个字段表示该记录的权重,权重为大于1的值  

 

 

  •     # sql_joined_field    = tags from query; SELECT docid, CONCAT(‘tag’,tagid) FROM tags ORDER BY docid ASC  

 

 

  •     # sql_joined_field    = wtags from payload-query; SELECT docid, tag, tagweight FROM tags ORDER BY docid ASC  

 

 

  •   

 

 

  •   

 

 

  •     # file based field declaration  

 

 

  •     #  

 

 

  •     # content of this field is treated as a file name  

 

 

  •     # and the file gets loaded and indexed in place of a field  

 

 

  •     #  

 

 

  •     # max file size is limited by max_file_field_buffer indexer setting  

 

 

  •     # file IO errors are non-fatal and get reported as warnings  

 

 

  •     # 把字段声明放入文件  

 

 

  •     # sql_file_field        = content_file_path  

 

 

  •   

 

 

  •   

 

 

  •     # range query setup, query that must return min and max ID values  

 

 

  •     # optional, default is empty  

 

 

  •     #   

 

 

  •     # sql_query will need to reference $start and $end boundaries  

 

 

  •     # if using ranged query:  

 

 

  •     # 分区查询,防止MYSQL死锁  

 

 

  •     # sql_query        = \  

 

 

  •     #    SELECT doc.id, doc.id AS group, doc.title, doc.data \  

 

 

  •     #    FROM documents doc \  

 

 

  •     #    WHERE id>=$start AND id<=$end  

 

 

  •     #  

 

 

  •     # sql_query_range        = SELECT MIN(id),MAX(id) FROM documents  

 

 

  •   

 

 

  •   

 

 

  •     # range query step  

 

 

  •     # optional, default is 1024  

 

 

  •     # 分区查询跳步  

 

 

  •     # sql_range_step        = 1000  

 

 

  •   

 

 

  •       

 

 

  •       

 

 

  •       

 

 

  •     # unsigned integer attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # optional bit size can be specified, default is 32  

 

 

  •     # 声明无符号数字段  

 

 

  •     #sql_attr_uint        = target_type  

 

 

  •     # sql_attr_uint        = forum_id:9 # 9 bits for forum_id  

 

 

  •     #sql_attr_uint        = group_id  

 

 

  •     #声明BOOL字段  

 

 

  •     # boolean attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # equivalent to sql_attr_uint with 1-bit size  

 

 

  •     #  

 

 

  •     # sql_attr_bool        = is_deleted  

 

 

  •   

 

 

  •   

 

 

  •     # bigint attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # declares a signed (unlike uint!) 64-bit attribute  

 

 

  •     # 声明长整字段  

 

 

  •     # sql_attr_bigint        = my_bigint_id  

 

 

  •   

 

 

  •   

 

 

  •     # UNIX timestamp attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # similar to integer, but can also be used in date functions  

 

 

  •     # 声明时间字段  

 

 

  •     # sql_attr_timestamp    = posted_ts  

 

 

  •     # sql_attr_timestamp    = last_edited_ts  

 

 

  •     #sql_attr_timestamp    = date_added  

 

 

  •       

 

 

  •     # string ordinal attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # sorts strings (bytewise), and stores their indexes in the sorted list  

 

 

  •     # sorting by this attr is equivalent to sorting by the original strings  

 

 

  •     # 声明字符串字段 用于排序等,但此字段不会被存储  

 

 

  •     # sql_attr_str2ordinal    = author_name  

 

 

  •   

 

 

  •   

 

 

  •     # floating point attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # values are stored in single precision, 32-bit IEEE 754 format  

 

 

  •     # 声明浮点字段  

 

 

  •     # sql_attr_float        = lat_radians  

 

 

  •     # sql_attr_float        = long_radians  

 

 

  •   

 

 

  •   

 

 

  •     # multi-valued attribute (MVA) attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # MVA values are variable length lists of unsigned 32-bit integers  

 

 

  •     #  

 

 

  •     # syntax is ATTR-TYPE ATTR-NAME ‘from’ SOURCE-TYPE [;QUERY] [;RANGE-QUERY]  

 

 

  •     # ATTR-TYPE is ‘uint’ or ‘timestamp’  

 

 

  •     # SOURCE-TYPE is ‘field’, ‘query’, or ‘ranged-query’  

 

 

  •     # QUERY is SQL query used to fetch all ( docid, attrvalue ) pairs  

 

 

  •     # RANGE-QUERY is SQL query used to fetch min and max ID values, similar to ‘sql_query_range’  

 

 

  •     # 声明复合字段  

 

 

  •     # sql_attr_multi        = uint tag from query; SELECT docid, tagid FROM tags  

 

 

  •     # sql_attr_multi        = uint tag from ranged-query; \  

 

 

  •     #    SELECT docid, tagid FROM tags WHERE id>=$start AND id<=$end; \  

 

 

  •     #    SELECT MIN(docid), MAX(docid) FROM tags  

 

 

  •   

 

 

  •   

 

 

  •     # string attribute declaration  

 

 

  •     # multi-value (an arbitrary number of these is allowed), optional  

 

 

  •     # lets you store and retrieve strings  

 

 

  •     # 只是把数据存储,但不会索引改字段  

 

 

  •     # sql_attr_string        = stitle  

 

 

  •   

 

 

  •   

 

 

  •     # wordcount attribute declaration  

 

 

  •     # multi-value (an arbitrary number of these is allowed), optional  

 

 

  •     # lets you count the words at indexing time  

 

 

  •     # 将转化成关键字的字段,用于提高匹配率  

 

 

  •     # sql_attr_str2wordcount    = stitle  

 

 

  •   

 

 

  •   

 

 

  •     # combined field plus attribute declaration (from a single column)  

 

 

  •     # stores column as an attribute, but also indexes it as a full-text field  

 

 

  •     # 跟sql_attr_string不同是该属性加入索引  

 

 

  •     # sql_field_string    = author  

 

 

  •     # sql_field_str2wordcount    = title  

 

 

  •   

 

 

  •       

 

 

  •     # post-query, executed on sql_query completion  

 

 

  •     # optional, default is empty  

 

 

  •     # 取后查询  

 

 

  •     # sql_query_post        =  

 

 

  •   

 

 

  •       

 

 

  •     # post-index-query, executed on successful indexing completion  

 

 

  •     # optional, default is empty  

 

 

  •     # $maxid expands to max document ID actually fetched from DB  

 

 

  •     # 索引后查询  

 

 

  •     # sql_query_post_index    = REPLACE INTO counters ( id, val ) \  

 

 

  •     #    VALUES ( ‘max_indexed_id’, $maxid )  

 

 

  •   

 

 

  •   

 

 

  •     # ranged query throttling, in milliseconds  

 

 

  •     # optional, default is 0 which means no delay  

 

 

  •     # enforces given delay before each query step  

 

 

  •     #分区查询的时间间隔  

 

 

  •     sql_ranged_throttle    = 0  

 

 

  •   

 

 

  •     # document info query, ONLY for CLI search (ie. testing and debugging)  

 

 

  •     # optional, default is empty  

 

 

  •     # must contain $id macro and must fetch the document by that id  

 

 

  •     #命令行调试查询结果用  

 

 

  •     sql_query_info        = SELECT * FROM ko_link WHERE id=$id  

 

 

  •   

 

 

  •     # kill-list query, fetches the document IDs for kill-list  

 

 

  •     # k-list will suppress matches from preceding indexes in the same query  

 

 

  •     # optional, default is empty  

 

 

  •     ##清理指定查询ID列表,对于数据的更改  

 

 

  •     # sql_query_killlist    = SELECT id FROM documents WHERE edited>=@last_reindex  

 

 

  •   

 

 

  •   

 

 

  •     # columns to unpack on indexer side when indexing  

 

 

  •     # multi-value, optional, default is empty list  

 

 

  •     # 启用ZIP压缩 可以降低系统负载 但必须保证zlib库zlib-dev库可用  

 

 

  •     # unpack_zlib        = zlib_column  

 

 

  •     # unpack_mysqlcompress    = compressed_column  

 

 

  •     # unpack_mysqlcompress    = compressed_column_2  

 

 

  •   

 

 

  •   

 

 

  •     # maximum unpacked length allowed in MySQL COMPRESS() unpacker  

 

 

  •     # optional, default is 16M  

 

 

  •     # 压缩缓存区大小 不能小于字段存储值  

 

 

  •     # unpack_mysqlcompress_maxsize    = 16M  

 

 

  •   

 

 

  •   

 

 

  •     #####################################################################  

 

 

  •     ## xmlpipe2 配置  

 

 

  •     #####################################################################  

 

 

  •   

 

 

  •     # type            = xmlpipe  

 

 

  •   

 

 

  •     # shell command to invoke xmlpipe stream producer  

 

 

  •     # mandatory  

 

 

  •     #  

 

 

  •     # xmlpipe_command        = cat /usr/local/sphinx/var/test.xml  

 

 

  •   

 

 

  •     # xmlpipe2 field declaration  

 

 

  •     # multi-value, optional, default is empty  

 

 

  •     #  

 

 

  •     # xmlpipe_field        = subject  

 

 

  •     # xmlpipe_field        = content  

 

 

  •   

 

 

  •   

 

 

  •     # xmlpipe2 attribute declaration  

 

 

  •     # multi-value, optional, default is empty  

 

 

  •     # all xmlpipe_attr_XXX options are fully similar to sql_attr_XXX  

 

 

  •     #  

 

 

  •     # xmlpipe_attr_timestamp    = published  

 

 

  •     # xmlpipe_attr_uint    = author_id  

 

 

  •   

 

 

  •   

 

 

  •     # perform UTF-8 validation, and filter out incorrect codes  

 

 

  •     # avoids XML parser choking on non-UTF-8 documents  

 

 

  •     # optional, default is 0  

 

 

  •     #  

 

 

  •     # xmlpipe_fixup_utf8    = 1  

 

 

  • }  

 

 

  •   

 

 

  •   

 

 

  • # inherited source example  

 

 

  • # 继承数据源  

 

 

  • # all the parameters are copied from the parent source,  

 

 

  • # and may then be overridden in this source definition  

 

 

  • #source src1throttled : src1  

 

 

  • #{  

 

 

  • #    sql_ranged_throttle    = 100  

 

 

  • #}  

 

 

  •   

 

 

  • #############################################################################  

 

 

  • ## index definition  

 

 

  • #############################################################################  

 

 

  •   

 

 

  • # local index example  

 

 

  • #  

 

 

  • # this is an index which is stored locally in the filesystem  

 

 

  • #  

 

 

  • # all indexing-time options (such as morphology and charsets)  

 

 

  • # are configured per local index  

 

 

  • index test1  

 

 

  • {  

 

 

  •     # index type  

 

 

  •     # optional, default is ‘plain’  

 

 

  •     # known values are ‘plain’, ‘distributed’, and ‘rt’ (see samples below)   

 

 

  •     #索引类型 本地 分布式   

 

 

  •     # type            = plain  

 

 

  •   

 

 

  •     # document source(s) to index  

 

 

  •     # multi-value, mandatory  

 

 

  •     # document IDs must be globally unique across all sources  

 

 

  •     #数据源,可以多个数据源  

 

 

  •     source            = src1  

 

 

  •   

 

 

  •     # index files path and file name, without extension  

 

 

  •     # mandatory, path must be writable, extensions will be auto-appended  

 

 

  •     # 索引保存路径  

 

 

  •     path            = /usr/local/sphinx/var/data/test1  

 

 

  •   

 

 

  •     # document attribute values (docinfo) storage mode  

 

 

  •     # optional, default is ‘extern’  

 

 

  •     # known values are ‘none’, ‘extern’ and ‘inline’  

 

 

  •     #索引存储方式  

 

 

  •     docinfo            = extern  

 

 

  •   

 

 

  •     # memory locking for cached data (.spa and .spi), to prevent swapping  

 

 

  •     # optional, default is 0 (do not mlock)  

 

 

  •     # requires searchd to be run from root  

 

 

  •     #内存锁定 需要保证足够权限  

 

 

  •     mlock            = 0  

 

 

  •   

 

 

  •     # a list of morphology preprocessors to apply  

 

 

  •     # optional, default is empty  

 

 

  •     #  

 

 

  •     # builtin preprocessors are ‘none’, ‘stem_en’, ‘stem_ru’, ‘stem_enru’,  

 

 

  •     # ‘soundex’, and ‘metaphone’; additional preprocessors available from  

 

 

  •     # libstemmer are ‘libstemmer_XXX’, where XXX is algorithm code  

 

 

  •     # (see libstemmer_c/libstemmer/modules.txt)  

 

 

  •     # 词语提取器  

 

 

  •     # morphology        = stem_en, stem_ru, soundex  

 

 

  •     # morphology        = libstemmer_german  

 

 

  •     # morphology        = libstemmer_sv  

 

 

  •     morphology        = stem_en  

 

 

  •   

 

 

  •     # minimum word length at which to enable stemming  

 

 

  •     # optional, default is 1 (stem everything)  

 

 

  •     # 词干化的最小词长  

 

 

  •     # min_stemming_len    = 1  

 

 

  •   

 

 

  •   

 

 

  •     # stopword files list (space separated)  

 

 

  •     # optional, default is empty  

 

 

  •     # contents are plain text, charset_table and stemming are both applied  

 

 

  •     # 停用搜索词  

 

 

  •     # stopwords        = /usr/local/sphinx/var/data/stopwords.txt  

 

 

  •   

 

 

  •   

 

 

  •     # wordforms file, in “mapfrom > mapto” plain text format  

 

 

  •     # optional, default is empty  

 

 

  •     # 词型字典 可用spelldump工具生成  

 

 

  •     # wordforms        = /usr/local/sphinx/var/data/wordforms.txt  

 

 

  •   

 

 

  •   

 

 

  •     # tokenizing exceptions file  

 

 

  •     # optional, default is empty  

 

 

  •     #Token特例文件,就是有些词是完整词意,不能拆分索引如a&t 跟a & t  

 

 

  •     # plain text, case sensitive, space insensitive in map-from part  

 

 

  •     # one “Map Several Words => ToASingleOne” entry per line  

 

 

  •     #  

 

 

  •     # exceptions        = /usr/local/sphinx/var/data/exceptions.txt  

 

 

  •   

 

 

  •   

 

 

  •     # minimum indexed word length  

 

 

  •     # default is 1 (index everything)  

 

 

  •     #  最小索引长度,就是小于指定长度的词不被索引  

 

 

  •     min_word_len        = 1  

 

 

  •   

 

 

  •     # charset encoding type  

 

 

  •     # optional, default is ‘sbcs’  

 

 

  •     # known types are ‘sbcs’ (Single Byte CharSet) and ‘utf-8’  

 

 

  •     # 字符编码  

 

 

  •     charset_type        = utf-8  

 

 

  •   

 

 

  •     # charset definition and case folding rules “table”  

 

 

  •     # optional, default value depends on charset_type  

 

 

  •     #  

 

 

  •     # defaults are configured to include English and Russian characters only  

 

 

  •     # you need to change the table to include additional ones  

 

 

  •     # this behavior MAY change in future versions  

 

 

  •     #  

 

 

  •     # ‘sbcs’ default value is  

 

 

  •     # charset_table        = 0..9, A..Z->a..z, _, a..z, U+A8->U+B8, U+B8, U+C0..U+DF->U+E0..U+FF, U+E0..U+FF  

 

 

  •     # 转换字符表  

 

 

  •     # ‘utf-8’ default value is  

 

 

  •     # charset_table        = 0..9, A..Z->a..z, _, a..z, U+410..U+42F->U+430..U+44F, U+430..U+44F  

 

 

  •   

 

 

  •   

 

 

  •     # ignored characters list  

 

 

  •     # optional, default value is empty  

 

 

  •     #  忽略字符表  

 

 

  •     # ignore_chars        = U+00AD  

 

 

  •   

 

 

  •   

 

 

  •     # minimum word prefix length to index  

 

 

  •     # optional, default is 0 (do not index prefixes)  

 

 

  •     #索引的最小前缀长度,小心使用,索引和搜索的时间皆会恶化  

 

 

  •     # min_prefix_len        = 0  

 

 

  •   

 

 

  •   

 

 

  •     # minimum word infix length to index  

 

 

  •     # optional, default is 0 (do not index infixes)  

 

 

  •     #索引的最小中缀长度 小心使用,索引和搜索的时间皆会恶化  

 

 

  •     # min_infix_len        = 0  

 

 

  •   

 

 

  •   

 

 

  •     # list of fields to limit prefix/infix indexing to  

 

 

  •     # optional, default value is empty (index all fields in prefix/infix mode)  

 

 

  •     # 未知  

 

 

  •     # prefix_fields        = filename  

 

 

  •     # infix_fields        = url, domain  

 

 

  •   

 

 

  •   

 

 

  •     # enable star-syntax (wildcards) when searching prefix/infix indexes  

 

 

  •     # search-time only, does not affect indexing, can be 0 or 1  

 

 

  •     # optional, default is 0 (do not use wildcard syntax)  

 

 

  •     # 启用星号语法  

 

 

  •     # enable_star        = 1  

 

 

  •   

 

 

  •   

 

 

  •     # expand keywords with exact forms and/or stars when searching fit indexes  

 

 

  •     # search-time only, does not affect indexing, can be 0 or 1  

 

 

  •     # optional, default is 0 (do not expand keywords)  

 

 

  •     # 扩大搜索关键字 形式如: running -> ( running | *running* | =running )  

 

 

  •     # expand_keywords        = 1  

 

 

  •   

 

 

  •       

 

 

  •     # n-gram length to index, for CJK indexing  

 

 

  •     # only supports 0 and 1 for now, other lengths to be implemented  

 

 

  •     # optional, default is 0 (disable n-grams)  

 

 

  •     # 中文等其他语言的基本支持  

 

 

  •     # ngram_len        = 1  

 

 

  •   

 

 

  •   

 

 

  •     # n-gram characters list, for CJK indexing  

 

 

  •     # optional, default is empty  

 

 

  •     #中文或其他语言的值范围  

 

 

  •     # ngram_chars        = U+3000..U+2FA1F  

 

 

  •   

 

 

  •   

 

 

  •     # phrase boundary characters list  

 

 

  •     # optional, default is empty  

 

 

  •     # 边界符  

 

 

  •     # phrase_boundary        = ., ?, !, U+2026 # horizontal ellipsis  

 

 

  •   

 

 

  •   

 

 

  •     # phrase boundary word position increment  

 

 

  •     # optional, default is 0  

 

 

  •     # 边界符增量  

 

 

  •     # phrase_boundary_step    = 100  

 

 

  •   

 

 

  •   

 

 

  •     # blended characters list  

 

 

  •     # blended chars are indexed both as separators and valid characters  

 

 

  •     # for instance, AT&T will results in 3 tokens (“at”, “t”, and “at&t”)  

 

 

  •     # optional, default is empty  

 

 

  •     # 混合字符列表  

 

 

  •     # blend_chars        = +, &, U+23  

 

 

  •   

 

 

  •   

 

 

  •     # blended token indexing mode  

 

 

  •     # a comma separated list of blended token indexing variants  

 

 

  •     # known variants are trim_none, trim_head, trim_tail, trim_both, skip_pure  

 

 

  •     # optional, default is trim_none  

 

 

  •     #未知  

 

 

  •     # blend_mode        = trim_tail, skip_pure  

 

 

  •   

 

 

  •   

 

 

  •     # whether to strip HTML tags from incoming documents  

 

 

  •     # known values are 0 (do not strip) and 1 (do strip)  

 

 

  •     # optional, default is 0  

 

 

  •     # 删除HTML标签 (小心文本被删除)  

 

 

  •     html_strip        = 0  

 

 

  •   

 

 

  •     # what HTML attributes to index if stripping HTML  

 

 

  •     # optional, default is empty (do not index anything)  

 

 

  •     # 保留的HTML标签  

 

 

  •     # html_index_attrs    = img=alt,title; a=title;  

 

 

  •   

 

 

  •   

 

 

  •     # what HTML elements contents to strip  

 

 

  •     # optional, default is empty (do not strip element contents)  

 

 

  •     # 不但删除标签,其包含的文本也将删除  

 

 

  •     # html_remove_elements    = style, script  

 

 

  •   

 

 

  •   

 

 

  •     # whether to preopen index data files on startup  

 

 

  •     # optional, default is 0 (do not preopen), searchd-only  

 

 

  •     # 预先打开索引还是每次查询的时候在打开索引  

 

 

  •     # preopen            = 1  

 

 

  •   

 

 

  •   

 

 

  •     # whether to keep dictionary (.spi) on disk, or cache it in RAM  

 

 

  •     # optional, default is 0 (cache in RAM), searchd-only  

 

 

  •     # 将字典文件是否保存在内存中  

 

 

  •     # ondisk_dict        = 1  

 

 

  •   

 

 

  •   

 

 

  •     # whether to enable in-place inversion (2x less disk, 90-95% speed)  

 

 

  •     # optional, default is 0 (use separate temporary files), indexer-only  

 

 

  •     # 是否启用原地索引倒转 将少磁盘使用 性能会有一点损失  

 

 

  •     # inplace_enable        = 1  

 

 

  •   

 

 

  •   

 

 

  •     # in-place fine-tuning options  

 

 

  •     # optional, defaults are listed below  

 

 

  •     #微调原地倒转  

 

 

  •     # inplace_hit_gap        = 0 # preallocated hitlist gap size   

 

 

  •     # inplace_docinfo_gap    = 0 # preallocated docinfo gap size  

 

 

  •     # inplace_reloc_factor    = 0.1 # relocation buffer size within arena  

 

 

  •     # inplace_write_factor    = 0.1 # write buffer size within arena  

 

 

  •   

 

 

  •   

 

 

  •     # whether to index original keywords along with stemmed versions  

 

 

  •     # enables “=exactform” operator to work  

 

 

  •     # optional, default is 0  

 

 

  •     # 是否在索引原关键词的词干化/重映射后的形式的同时也索引原词  

 

 

  •     # index_exact_words    = 1  

 

 

  •   

 

 

  •   

 

 

  •     # position increment on overshort (less that min_word_len) words  

 

 

  •     # optional, allowed values are 0 and 1, default is 1  

 

 

  •     #在经过过短的词(比 min_word_len短的词)处后增加位置值  

 

 

  •     # overshort_step        = 1  

 

 

  •   

 

 

  •   

 

 

  •     # position increment on stopword  

 

 

  •     # optional, allowed values are 0 and 1, default is 1  

 

 

  •     #在经过 停用词 处后增加位置值可选选项  

 

 

  •     # stopword_step        = 1  

 

 

  •   

 

 

  •   

 

 

  •     # hitless words list  

 

 

  •     # positions for these keywords will not be stored in the index  

 

 

  •     # optional, allowed values are ‘all’, or a list file name  

 

 

  •     # 不能中断的字符列表  

 

 

  •     # hitless_words        = all  

 

 

  •     # hitless_words        = hitless.txt #字符文件  

 

 

  •   

 

 

  •   

 

 

  •     # detect and index sentence and paragraph boundaries  

 

 

  •     # required for the SENTENCE and PARAGRAPH operators to work  

 

 

  •     # optional, allowed values are 0 and 1, default is 0  

 

 

  •     # 是否检查标签合并 针对HTML  

 

 

  •     # index_sp            = 1  

 

 

  •   

 

 

  •   

 

 

  •     # index zones, delimited by HTML/XML tags  

 

 

  •     # a comma separated list of tags and wildcards  

 

 

  •     # required for the ZONE operator to work  

 

 

  •     # optional, default is empty string (do not index zones)  

 

 

  •     # 对HTML标签的权重  

 

 

  •     # index_zones        = title, h*, th  

 

 

  • }  

 

 

  •   

 

 

  •   

 

 

  • # inherited index example  

 

 

  • # 索引继承  

 

 

  • # all the parameters are copied from the parent index,  

 

 

  • # and may then be overridden in this index definition  

 

 

  • #index test1stemmed : test1  

 

 

  • #{  

 

 

  • #    path            = /usr/local/sphinx/var/data/test1stemmed  

 

 

  • #    morphology        = stem_en  

 

 

  • #}  

 

 

  •   

 

 

  •   

 

 

  • # distributed index example  

 

 

  • #  

 

 

  • # this is a virtual index which can NOT be directly indexed,  

 

 

  • # and only contains references to other local and/or remote indexes  

 

 

  • #index dist1  

 

 

  • #{  

 

 

  • #分布式索引配置  

 

 

  •     # ‘distributed’ index type MUST be specified  

 

 

  • #    type            = distributed  

 

 

  •   

 

 

  •     # local index to be searched  

 

 

  •     # there can be many local indexes configured  

 

 

  • #    local            = test1  

 

 

  • #    local            = test1stemmed  

 

 

  •   

 

 

  •     # remote agent  

 

 

  •     # multiple remote agents may be specified  

 

 

  •     # syntax for TCP connections is ‘hostname:port:index1,[index2[,…]]’  

 

 

  •     # syntax for local UNIX connections is ‘/path/to/socket:index1,[index2[,…]]’  

 

 

  • #    agent            = localhost:9313:remote1  

 

 

  • #    agent            = localhost:9314:remote2,remote3  

 

 

  •     # agent            = /var/run/searchd.sock:remote4  

 

 

  •   

 

 

  •     # blackhole remote agent, for debugging/testing  

 

 

  •     # network errors and search results will be ignored  

 

 

  •     #  

 

 

  •     # agent_blackhole        = testbox:9312:testindex1,testindex2  

 

 

  •   

 

 

  •   

 

 

  •     # remote agent connection timeout, milliseconds  

 

 

  •     # optional, default is 1000 ms, ie. 1 sec  

 

 

  • #    agent_connect_timeout    = 1000  

 

 

  •   

 

 

  •     # remote agent query timeout, milliseconds  

 

 

  •     # optional, default is 3000 ms, ie. 3 sec  

 

 

  • #    agent_query_timeout    = 3000  

 

 

  • #}  

 

 

  •   

 

 

  •   

 

 

  • # realtime index example  

 

 

  • #  

 

 

  • # you can run INSERT, REPLACE, and DELETE on this index on the fly  

 

 

  • # using MySQL protocol (see ‘listen’ directive below)  

 

 

  • #index rt  

 

 

  • #{  

 

 

  •     # ‘rt’ index type must be specified to use RT index  

 

 

  • #    type            = rt  

 

 

  •   

 

 

  •     # index files path and file name, without extension  

 

 

  •     # mandatory, path must be writable, extensions will be auto-appended  

 

 

  •   

 

 

  • #    path            = /usr/local/sphinx/var/data/rt  

 

 

  •   

 

 

  •     # RAM chunk size limit  

 

 

  •     # RT index will keep at most this much data in RAM, then flush to disk  

 

 

  •     # optional, default is 32M  

 

 

  •     #  

 

 

  •     # rt_mem_limit        = 512M  

 

 

  •   

 

 

  •     # full-text field declaration  

 

 

  •     # multi-value, mandatory  

 

 

  • #    rt_field        = title  

 

 

  • #    rt_field        = content  

 

 

  •   

 

 

  •     # unsigned integer attribute declaration  

 

 

  •     # multi-value (an arbitrary number of attributes is allowed), optional  

 

 

  •     # declares an unsigned 32-bit attribute  

 

 

  • #    rt_attr_uint        = gid  

 

 

  •   

 

 

  •     # RT indexes currently support the following attribute types:  

 

 

  •     # uint, bigint, float, timestamp, string  

 

 

  •     #  

 

 

  •     # rt_attr_bigint        = guid  

 

 

  •     # rt_attr_float        = gpa  

 

 

  •     # rt_attr_timestamp    = ts_added  

 

 

  •     # rt_attr_string        = author  

 

 

  • #}  

 

 

  •   

 

 

  • #############################################################################  

 

 

  • ## indexer settings  

 

 

  • #############################################################################  

 

 

  •   

 

 

  • indexer  

 

 

  • {  

 

 

  •     #索引过程内存使用限制。可选选项,默认32M。   

 

 

  •     # memory limit, in bytes, kiloytes (16384K) or megabytes (256M)  

 

 

  •     # optional, default is 32M, max is 2047M, recommended is 256M to 1024M  

 

 

  •     mem_limit        = 32M  

 

 

  •   

 

 

  •     # maximum IO calls per second (for I/O throttling)  

 

 

  •     # optional, default is 0 (unlimited)  

 

 

  •     # 每秒最大I/O操作次数,用于限制I/O操作。可选选项,默认为0(无限制)。   

 

 

  •     # max_iops        = 40  

 

 

  •   

 

 

  •   

 

 

  •     # maximum IO call size, bytes (for I/O throttling)  

 

 

  •     # optional, default is 0 (unlimited)  

 

 

  •     # 最大允许的I/O操作大小,以字节为单位,用于I/O节流。可选选项,默认为0(不限制)。   

 

 

  •     # max_iosize        = 1048576  

 

 

  •   

 

 

  •   

 

 

  •     # maximum xmlpipe2 field length, bytes  

 

 

  •     # optional, default is 2M  

 

 

  •     # 对于XMLLpipe2数据源允许的最大的域大小  

 

 

  •     # max_xmlpipe2_field    = 4M  

 

 

  •   

 

 

  •   

 

 

  •     # write buffer size, bytes  

 

 

  •     # several (currently up to 4) buffers will be allocated  

 

 

  •     # write buffers are allocated in addition to mem_limit  

 

 

  •     # optional, default is 1M  

 

 

  •     # 写缓冲区的大小,单位是字节。可选选项,默认值是1MB。   

 

 

  •     # write_buffer        = 1M  

 

 

  •   

 

 

  •   

 

 

  •     # maximum file field adaptive buffer size  

 

 

  •     # optional, default is 8M, minimum is 1M  

 

 

  •     #  

 

 

  •     # max_file_field_buffer    = 32M  

 

 

  • }  

 

 

  •   

 

 

  • #############################################################################  

 

 

  • ## searchd settings  

 

 

  • #############################################################################  

 

 

  •   

 

 

  • searchd  

 

 

  • {  

 

 

  •     # [hostname:]port[:protocol], or /unix/socket/path to listen on  

 

 

  •     # known protocols are ‘sphinx’ (SphinxAPI) and ‘mysql41’ (SphinxQL)  

 

 

  •     #  

 

 

  •     # multi-value, multiple listen points are allowed  

 

 

  •     # optional, defaults are 9312:sphinx and 9306:mysql41, as below  

 

 

  •     #  

 

 

  •     # listen            = 127.0.0.1  

 

 

  •     # listen            = 192.168.0.1:9312  

 

 

  •     # listen            = 9312  

 

 

  •     # listen            = /var/run/searchd.sock  

 

 

  •     listen            = 9312  

 

 

  •     #listen            = 9306:mysql41  

 

 

  •   

 

 

  •     # log file, searchd run info is logged here  

 

 

  •     # optional, default is ‘searchd.log’  

 

 

  •     # 全部searchd运行时事件会被记录在这个日志文件中。   

 

 

  •     log            = /usr/local/sphinx/var/log/searchd.log  

 

 

  •   

 

 

  •     # query log file, all search queries are logged here  

 

 

  •     # optional, default is empty (do not log queries)  

 

 

  •     # 全部搜索查询会被记录在此文件中。  

 

 

  •     query_log        = /usr/local/sphinx/var/log/query.log  

 

 

  •   

 

 

  •     # client read timeout, seconds  

 

 

  •     # optional, default is 5  

 

 

  •     #网络客户端请求的读超时时间,单位是秒。  

 

 

  •     read_timeout        = 5  

 

 

  •   

 

 

  •     # request timeout, seconds  

 

 

  •     # optional, default is 5 minutes  

 

 

  •     #在使用持久连接时,两次查询之间等待的最长时间(单位是秒)。  

 

 

  •     client_timeout        = 300  

 

 

  •   

 

 

  •     # maximum amount of children to fork (concurrent searches to run)  

 

 

  •     # optional, default is 0 (unlimited)  

 

 

  •     #子进程的最大数量 ,用来控制服务器负载。任何时候不可能有比此设置值更多的搜索同时运行。当达到限制时,新的输入客户端会被用临时失败(SEARCH_RETRY)状态码驳回,同时给出一个声明服务器已到最大连接限制的消息。   

 

 

  •     max_children        = 30  

 

 

  •   

 

 

  •     # PID file, searchd process ID file name  

 

 

  •     # mandatory  

 

 

  •     #进程ID文件  

 

 

  •     pid_file        = /usr/local/sphinx/var/log/searchd.pid  

 

 

  •   

 

 

  •     # max amount of matches the daemon ever keeps in RAM, per-index  

 

 

  •     # WARNING, THERE’S ALSO PER-QUERY LIMIT, SEE SetLimits() API CALL  

 

 

  •     # default is 1000 (just like Google)  

 

 

  •     #守护进程在内存中为每个索引所保持并返回给客户端的匹配数目的最大值。  

 

 

  •     max_matches        = 1000  

 

 

  •   

 

 

  •     # seamless rotate, prevents rotate stalls if precaching huge datasets  

 

 

  •     # optional, default is 1  

 

 

  •     #防止 searchd 轮换在需要预取大量数据的索引时停止响应。可选选项,默认为1(启用无缝(seamless)轮换)。   

 

 

  •     seamless_rotate        = 1  

 

 

  •   

 

 

  •     # whether to forcibly preopen all indexes on startup  

 

 

  •     # optional, default is 1 (preopen everything)  

 

 

  •     #是否在启动是强制重新打开所有索引文件。可选选项,默认为0(不重新打开)。  

 

 

  •     preopen_indexes        = 1  

 

 

  •   

 

 

  •     # whether to unlink .old index copies on succesful rotation.  

 

 

  •     # optional, default is 1 (do unlink)  

 

 

  •     #索引轮换成功之后,是否删除以.old为扩展名的索引拷贝。可选选项,默认为1(删除这些索引拷贝)。   

 

 

  •     unlink_old        = 1  

 

 

  •   

 

 

  •     # attribute updates periodic flush timeout, seconds  

 

 

  •     # updates will be automatically dumped to disk this frequently  

 

 

  •     # optional, default is 0 (disable periodic flush)  

 

 

  •     # UpdateAttributes() 调用时候更新是否隔一段时间写入磁盘  

 

 

  •     # attr_flush_period    = 900  

 

 

  •   

 

 

  •   

 

 

  •     # instance-wide ondisk_dict defaults (per-index value take precedence)  

 

 

  •     # optional, default is 0 (precache all dictionaries in RAM)  

 

 

  •     #对 ondisk_dict 指令的全局的默认值。 可选选项,默认值是0(将字典预先缓冲到内存)。  

 

 

  •     # ondisk_dict_default    = 1  

 

 

  •   

 

 

  •   

 

 

  •     # MVA updates pool size  

 

 

  •     # shared between all instances of searchd, disables attr flushes!  

 

 

  •     # optional, default size is 1M  

 

 

  •     #网络通讯时允许的最大的包的大小。  

 

 

  •     mva_updates_pool    = 1M  

 

 

  •   

 

 

  •     # max allowed network packet size  

 

 

  •     # limits both query packets from clients, and responses from agents  

 

 

  •     # optional, default size is 8M  

 

 

  •     #用于多值属性MVA更新的存储空间的共享池大小。  

 

 

  •     max_packet_size        = 8M  

 

 

  •   

 

 

  •     # crash log path  

 

 

  •     # searchd will (try to) log crashed query to ‘crash_log_path.PID’ file  

 

 

  •     # optional, default is empty (do not create crash logs)  

 

 

  •     #崩溃日志文件的路径  

 

 

  •     # crash_log_path        = /usr/local/sphinx/var/log/crash  

 

 

  •   

 

 

  •   

 

 

  •     # max allowed per-query filter count  

 

 

  •     # optional, default is 256  

 

 

  •     #每次查询允许设置的过滤器的最大个数。只用于内部检查,不直接影响内存使用或性能。  

 

 

  •     max_filters        = 256  

 

 

  •   

 

 

  •     # max allowed per-filter values count  

 

 

  •     # optional, default is 4096  

 

 

  •     #单个过滤器允许的值的最大个数。只用于内部检查,不直接影响内存使用或性能。  

 

 

  •     max_filter_values    = 4096  

 

 

  •   

 

 

  •   

 

 

  •     # socket listen queue length  

 

 

  •     # optional, default is 5  

 

 

  •     #TCP监听积压列表长度。无法如对的请求立即失败并收到“连接被拒”错误信息  

 

 

  •     # listen_backlog        = 5  

 

 

  •   

 

 

  •   

 

 

  •     # per-keyword read buffer size  

 

 

  •     # optional, default is 256K  

 

 

  •     #每个关键字的读缓冲区的大小。可选选项,默认值是256K。   

 

 

  •     # read_buffer        = 256K  

 

 

  •   

 

 

  •   

 

 

  •     # unhinted read size (currently used when reading hits)  

 

 

  •     # optional, default is 32K  

 

 

  •     #无提示时读操作的大小。可选选项,默认值是32K。  

 

 

  •     # read_unhinted        = 32K  

 

 

  •   

 

 

  •   

 

 

  •     # max allowed per-batch query count (aka multi-query count)  

 

 

  •     # optional, default is 32  

 

 

  •     #限制每批次的查询量。一个OPEN之后的查询量  

 

 

  •     max_batch_queries    = 32  

 

 

  •   

 

 

  •   

 

 

  •     # max common subtree document cache size, per-query  

 

 

  •     # optional, default is 0 (disable subtree optimization)  

 

 

  •     #  

 

 

  •     # subtree_docs_cache    = 4M  

 

 

  •   

 

 

  •   

 

 

  •     # max common subtree hit cache size, per-query  

 

 

  •     # optional, default is 0 (disable subtree optimization)  

 

 

  •     # 限制RAM使用一个共同的子树优化 默认不优化  

 

 

  •     # subtree_hits_cache    = 8M  

 

 

  •   

 

 

  •   

 

 

  •     # multi-processing mode (MPM)  

 

 

  •     # known values are none, fork, prefork, and threads  

 

 

  •     # optional, default is fork  

 

 

  •     # 工作方式   

 

 

  •     workers            = threads # for RT to work  

 

 

  •   

 

 

  •   

 

 

  •     # max threads to create for searching local parts of a distributed index  

 

 

  •     # optional, default is 0, which means disable multi-threaded searching  

 

 

  •     # should work with all MPMs (ie. does NOT require workers=threads)  

 

 

  •     #    

 

 

  •     # dist_threads        = 4  

 

 

  •   

 

 

  •   

 

 

  •     # binlog files path; use empty string to disable binlog  

 

 

  •     # optional, default is build-time configured data directory  

 

 

  •     # 二进制日志路径  

 

 

  •     # binlog_path        = # disable logging  

 

 

  •     # binlog_path        = /usr/local/sphinx/var/data # binlog.001 etc will be created there  

 

 

  •   

 

 

  •   

 

 

  •     # binlog flush/sync mode  

 

 

  •     # 0 means flush and sync every second  

 

 

  •     # 1 means flush and sync every transaction  

 

 

  •     # 2 means flush every transaction, sync every second  

 

 

  •     # optional, default is 2  

 

 

  •     # 日志刷新模式  

 

 

  •     # binlog_flush        = 2  

 

 

  •   

 

 

  •   

 

 

  •     # binlog per-file size limit  

 

 

  •     # optional, default is 128M, 0 means no limit  

 

 

  •     #最大日志大小  

 

 

  •     # binlog_max_log_size    = 256M  

 

 

  •   

 

 

  •   

 

 

  •     # per-thread stack size, only affects workers=threads mode  

 

 

  •     # optional, default is 64K  

 

 

  •     #每个线程的堆栈大小。  

 

 

  •     # thread_stack            = 128K  

 

 

  •   

 

 

  •   

 

 

  •     # per-keyword expansion limit (for dict=keywords prefix searches)  

 

 

  •     # optional, default is 0 (no limit)  

 

 

  •     # 扩大为一个关键字的最大数目  

 

 

  •     # expansion_limit        = 1000  

 

 

  •   

 

 

  •   

 

 

  •     # RT RAM chunks flush period  

 

 

  •     # optional, default is 0 (no periodic flush)  

 

 

  •     #RT索引在内存中检查的时间  

 

 

  •     # rt_flush_period        = 900  

 

 

  •   

 

 

  •   

 

 

  •     # query log file format  

 

 

  •     # optional, known values are plain and sphinxql, default is plain  

 

 

  •     # 查询日志格式  

 

 

  •     # query_log_format        = sphinxql  

 

 

  •   

 

 

  •   

 

 

  •     # version string returned to MySQL network protocol clients  

 

 

  •     # optional, default is empty (use Sphinx version)  

 

 

  •     # MYSQL版本  

 

 

  •     # mysql_version_string    = 5.0.37  

 

 

  •   

 

 

  •   

 

 

  •     # trusted plugin directory  

 

 

  •     # optional, default is empty (disable UDFs)  

 

 

  •     # 插件目录  

 

 

  •     # plugin_dir            = /usr/local/sphinx/lib  

 

 

  •   

 

 

  •   

 

 

  •     # default server-wide collation  

 

 

  •     # optional, default is libc_ci  

 

 

  •     # 链接字符集  

 

 

  •     # collation_server        = utf8_general_ci  

 

 

  •   

 

 

  •   

 

 

  •     # server-wide locale for libc based collations  

 

 

  •     # optional, default is C  

 

 

  •     # collation 选项  

 

 

  •     # collation_libc_locale    = ru_RU.UTF-8  

 

 

  •   

 

 

  •   

 

 

  •     # threaded server watchdog (only used in workers=threads mode)  

 

 

  •     # optional, values are 0 and 1, default is 1 (watchdog on)  

 

 

  •     # 是否启用服务器监控进程  

 

 

  •     # watchdog                = 1  

 

 

  •   

 

 

  •       

 

 

  •     # SphinxQL compatibility mode (legacy columns and their names)  

 

 

  •     # optional, default is 0 (SQL compliant syntax and result sets)  

 

 

  •     #sphinxql 兼容模式  

 

 

  •     # compat_sphinxql_magics    = 1  

 

 

  • }  

 

 

  •   

 

 

  • # –eof–  

 

 

建立索引:
/usr/local/sphinx/bin/indexer –config /usr/local/sphinx/etc/sphinx.conf index1
不停服务下索引: 
/usr/local/sphinx/bin/indexer –config /usr/local/sphinx/etc/sphinx.conf –all –rotate
启动索引服务,使PHP的客户端可用
/usr/local/sphinx/bin/searchd –config /usr/local/sphinx/etc/sphinx.conf 
建立PHP测试文件

 

<?php      $s = new SphinxClient;      setServer(“localhost”, 9312);      $s->setMatchMode(SPH_MATCH_ANY);      $s->setMaxQueryTime(3);      $result = $s->query(“test”);#查询     print_r ($result); ?>

 

 

运行即可

searchd 命令:

强行停止:

searchd –config /home/myuser/sphinx.conf –stop

 

安静停止:

searchd –config /home/myuser/sphinx.conf –stopwait

 

状态:

 

searchd –config /home/myuser/sphinx.conf –status

 

指定PID文件

searchd –config /home/myuser/sphinx.conf –pidfile /home/myuser/sphinx.pid

 

启动的为控制台模式:

searchd –config /home/myuser/sphinx.conf –console

 

只启动指定索引

searchd –index myindex

 

生成一些字典的工具软件:spelldump

indextool 一些转移等工具的软件

搜索字符串规则:

 

* operator OR:
hello | world

* operator NOT:
hello -world
hello !world

* field search operator:
@title hello @body world

* field position limit modifier (introduced in version 0.9.9-rc1):
@body[50] hello

* multiple-field search operator:
@(title,body) hello world

* all-field search operator:
@* hello

* phrase search operator:
“hello world”

* proximity search operator:
“hello world”~10

* quorum matching operator:
“the world is a wonderful place”/3

* strict order operator (aka operator “before”):
aaa << bbb << ccc

* exact form modifier (introduced in version 0.9.9-rc1):
raining =cats and =dogs

* field-start and field-end modifier (introduced in version 0.9.9-rc2):
^hello world$

* NEAR, generalized proximity operator (introduced in version
2.0.1-beta):
hello NEAR/3 world NEAR/4 “my test”

* SENTENCE operator (introduced in version 2.0.1-beta):
all SENTENCE words SENTENCE “in one sentence”

* PARAGRAPH operator (introduced in version 2.0.1-beta):
“Bill Gates” PARAGRAPH “Steve Jobs”

* zone limit operator:
ZONE:(h3,h4) only in these titles

 

表达式,支持函数等 日期用的是时间戳 (好像不是作为MYSQL存储引擎的时候用不到)

* Arithmetic operators: +, -, *, /, %, DIV, MOD
* Comparison operators: <, > <=, >=, =, <>
* Boolean operators: AND, OR, NOT
* Bitwise operators: &, |
* ABS()
* BIGINT()
* CEIL()
* COS()
* CRC32()
* DAY()
* EXP()
* FLOOR()
* GEODIST()
* IDIV()
* IF()
* IN()
* INTERVAL()
* LN()
* LOG10()
* LOG2()
* MAX()
* MIN()
* MONTH()
* NOW()
* POW()
* SIN()
* SINT()
* SQRT()
* YEAR()
* YEARMONTH()
* YEARMONTHDAY()

 

 

  1. <?php   
  2.   
  3. include_once ‘sphinxapi.php’;  
  4. $s = new SphinxClient();  
  5. $s->setServer(“localhost”, 9312);  
  6. $s->SetConnectTimeout ( 1 );//设置链接超时  
  7.   
  8.   
  9. /* 
  10. $s->AddQuery();//列表查询 
  11. $s->RunQueries ();//执行列表查询 
  12. $s->ResetFilters();//清除过滤条件 
  13. $s->BuildExcerpts($docs, $index, $words);//生成简要 
  14. $s->BuildKeywords($query, $index, $hits);//生成关键字 
  15. $s->GetLastError();//错误 
  16. $s->GetLastWarning();//警告 
  17. $s->FlushAttributes();//索引刷入硬盘 
  18. $s->IsConnectError();//链接错误 
  19. $s->ResetGroupBy();//重设分组 
  20.  
  21. $s->SetFieldWeights(array(‘sub_title’=>1));//加权最小为1 
  22. $s->SetIDRange($min, $max);//ID范围 
  23. $s->SetIndexWeights(array(‘test1’=>1));//索引权重 
  24. $s->Status();//服务是否可用 
  25. $s->UpdateAttributes($index, $attrs, $values);//更新硬盘索引 
  26. */  
  27. /* 
  28. 参考文档:http://www.coreseek.cn/docs/coreseek_4.1-sphinx_2.0.1-beta.html#matching-modes 
  29. SPH_MATCH_ALL, matches all query words (default mode); 
  30. SPH_MATCH_ANY, matches any of the query words; 
  31. SPH_MATCH_PHRASE, matches query as a phrase, requiring perfect match; 
  32. SPH_MATCH_BOOLEAN, matches query as a boolean expression (see Section 5.2, “Boolean query syntax”); 
  33. SPH_MATCH_EXTENDED, matches query as an expression in Sphinx internal query language (see Section 5.3, “Extended query syntax”). As of 0.9.9, this has been superceded by SPH_MATCH_EXTENDED2, providing additional functionality and better performance. The ident is retained for legacy application code that will continue to be compatible once Sphinx and its components, including the API, are upgraded. 
  34. SPH_MATCH_EXTENDED2, matches query using the second version of the Extended matching mode. 
  35. SPH_MATCH_FULLSCAN, m 
  36. */  
  37. $s->setMatchMode(SPH_MATCH_ANY);//匹配模式  
  38. $s->setMaxQueryTime(3);//查询超时  
  39. //$s->SetSelect ( $select );//设置返回的字段  
  40. /* 
  41. $cl->SetSelect ( “*, @weight+(user_karma+ln(pageviews))*0.1 AS myweight” ); 
  42. $cl->SetSelect ( “exp_years, salary_gbp*{$gbp_usd_rate} AS salary_usd, 
  43.    IF(age>40,1,0) AS over40″ ); 
  44. $cl->SetSelect ( “*, AVG(price) AS avgprice” ); 
  45.  */  
  46.   
  47. /* 
  48. $cl->SetGroupBy ( “category”, SPH_GROUPBY_ATTR, “@count desc” ); 
  49. $cl->SetGroupDistinct ( “vendor” ); 
  50. == 
  51. SELECT id, weight, all-attributes, 
  52.     COUNT(DISTINCT vendor) AS @distinct, 
  53.     COUNT(*) AS @count 
  54. FROM products 
  55. GROUP BY category 
  56. ORDER BY @count DESC 
  57. */  
  58. //$s->SetGroupBy ( $groupby, SPH_GROUPBY_ATTR, $groupsort );//汇总  
  59. //$s->SetGroupDistinct ( $distinct );//设置不重复字段  
  60.   
  61. $s->SetArrayResult ( true );//结果是否有ID  
  62.   
  63. /* 
  64.     SPH_SORT_RELEVANCE mode, that sorts by relevance in descending order (best matches first); 
  65.     SPH_SORT_ATTR_DESC mode, that sorts by an attribute in descending order (bigger attribute values first); 
  66.     SPH_SORT_ATTR_ASC mode, that sorts by an attribute in ascending order (smaller attribute values first); 
  67.     SPH_SORT_TIME_SEGMENTS mode, that sorts by time segments (last hour/day/week/month) in descending order, and then by relevance in descending order; 
  68.     SPH_SORT_EXTENDED mode, that sorts by SQL-like combination of columns in ASC/DESC order; 
  69.     SPH_SORT_EXPR mode, that sorts by an arithmetic expression. 
  70.  */  
  71. //$s->SetSortMode ( SPH_SORT_EXTENDED, $sortby );//排序模式  
  72.   
  73. /* 
  74. $s->SetOverride($attrname, $attrtype, $values); 
  75. $s->ResetOverrides();*/  
  76. /* 
  77. $s->SetRetries($count);//设置失败重试 
  78. $s->SetRankingMode($ranker);//设置排名模式 均适用于SPH_MATCH_EXTENDED2搜索 
  79.  
  80. //第3个参数当为true时,相当于$attribute!=$value,默认值是false 
  81. $s->SetFilter ( ‘target_type’, $filtervals );//设置过滤,值列表 
  82. $s->SetFilterFloatRange($attribute, $min, $max);//浮动范围 
  83. $s->SetFilterRange($attribute, $min, $max);//指定范围 
  84. $s->SetGeoAnchor($attrlat, $attrlong, $lat, $long); 
  85. */  
  86. //link  
  87. //$s->SetFilter ( ‘target_type’, array(1),true );  
  88.   
  89.   
  90. $s->SetLimits ( 0, 10 );//显示数量:开始 量 最大量 右偏移量  
  91. $result = $s->query(“good”,“team”);//查询  
  92.   
  93.   
  94. print_r($result);  

ImageImagick + PHP + Apache On WINDOWS

今天帮同事安装配置php_imagick,结果装是装上了apache也能正常启动,但是程序一new Imagick()就会导致Apache崩溃。

在google之后从Stack Overflow找到问题原因:

I’ve had the same issue today. You have to install version of Image Magick no higher than 6.6.4.0 – next builds are made using VC10 which seems to be incompatible with Apache VC9 + PHP5.3.x VC9.

 

ImageImagick dll for windows 在6.6.4以后用的都是VC10编译,所以不兼容vc9编译的php,虽然apache能正常启动,但是new Imagick的时候会导致apache崩溃。

解决办法就是安装低版本的ImageImagick

下载地址:http://image_magick.veidrodis.com/image_magick/binaries/

 

参考资料:

http://stackoverflow.com/questions/8608426/imagick-crash-with-php-5-3

http://www.elxsy.com/2009/07/installing-imagemagick-on-windows-and-using-with-php-imagick/

PHP 中的 XML 拉模式解析

src:http://www.wujianrong.com/archives/2007/04/php_xml.html

PHP 5 引入了新的类 XMLReader,用于读取可扩展标记语言(Extensible Markup Language,XML)。与 SimpleXML 或文档对象模型(Document Object Model,DOM)不同,XMLReader 以流模式进行操作。即它从头到尾读取文档。在文档后面的内容编译完成之前,可以先处理已编译好的文档前面的内容,从而实现非常快速、非常高效、非常节省地使用内存。需要处理的文档越大,这个特点就越发重要。

libxml

这里所说的 XMLReader API 位于 Gnome Project 中用于 C 和 C++ 的 libxml 库之上。实际上 XMLReader 只是在 libxml 的 XmlTextReader API 之上的很薄的 PHP 层。XmlTextReader 本身是模仿 .NET 的 XmlTextReader 类和 XmlReader 类,尽管并不具有与这些类相似的代码。

与 Simple API for XML (SAX) 不同,XMLReader 是推解析器,而不是拉解析器。这意味着程序是可以控制的。您将告诉解析器何时获取下一个文档片段,而不是在解析器看到文档后告诉您所看到的内容。您将请求内容,而不是对内容进行反应。从另一个角度来考虑这个问题:XMLReader 是 Iterator 设计模式的实现,而不是 Observer 设计模式的实现。

示例问题

先从简单例子开始讨论。假定正在编写 PHP 脚本,用来接收 XML-RPC 请求并生成响应。更具体一些,假定请求如清单 1 所示。文档的根元素是 methodCall,它包含 methodName 元素和 params 元素。方法的名称是 sqrt。params 元素包含一个 param 元素,param 元素包含 double,double 的平方根是希望得到的值。没有使用名称空间。

清单 1. XML-RPC 请求


<?xml version="1.0"?>
<methodCall>
<methodName>sqrt</methodName>
<params>
<param>
<value><double>36.0</double></value>
</param>
</params>
</methodCall>

下面是 PHP 脚本需要完成的工作:

  1. 检查方法名,如果不是 sqrt(它是该脚本懂得如何处理的惟一方法),则生成错误响应。
  2. 找到参数,如果参数不存在或参数类型错误,则生成错误响应。
  3. 另外,计算平方根。
  4. 在表单中返回结果,如清单 2 所示。

清单 2. XML-RPC 响应


<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value><double>6.0</double></value>
</param>
</params>
</methodResponse>

下面我们逐步展开说明。

初始化解析器并载入文档

第一步是创建新的解析器对象。创建操作很简单:

$reader = new XMLReader();

接着,需要为它提供一些用于解析的数据。对于 XML-RPC,这是超文本传输协议(Hypertext Transfer Protocol,HTTP)请求的原始主体。然后可以将该字符串传递到读取器的 XML() 函数:

填充原始发送数据

如果发现 $HTTP_RAW_POST_DATA 是空的,则将以下代码行添加到 php.ini 文件:

always_populate_raw_post_data = On
$request = $HTTP_RAW_POST_DATA;
$reader->XML($request);

可以解析任何字符串,无论它是从何处获取的。例如,可以是程序中的一串文字或从本地文件读取。还可以使用 open() 函数从外部 URL 载入数据。例如,下面的语句准备解析其中一个 Atom 提要:

$reader->XML('http://www.cafeaulait.org/today.atom');

无论是从何处获取原始数据,现在已建立了阅读器并为解析做好准备。

读取文档

read() 函数使解析器前进到下一个标记。最简单的方法是在 while 循环中遍历整个文档:

while ($reader->read()) {
// processing code goes here...
}

完成遍历后,关闭解析器以释放它所持有的任何资源,并且重置解析器以便用于下一个文档:

$reader->close();

在循环内部,将解析器放置在特殊节点上:元素的起点、元素的终点、文本节点、注释等等。通过检查以下属性,可以发现解析器正在查看的内容:

  • localName 是本地的、未带前缀的节点名。
  • name 是可能的节点前缀名。对于像注释这种没有名称的节点,包括 #comment、#text、#document 等等,与 DOM 中的一样。
  • namespaceURI 是节点名称空间的统一资源标识符(Uniform Resource Identifier,URI)。
  • nodeType 是代表节点类型的整数 —— 例如,2 代表属性节点,7 代表处理指令。
  • prefix 是节点的名称空间前缀。
  • value 是节点的下一个文本内容。
  • 如果节点有文本值,hasValue 值为 true;否则,值为 false。

当然,并非所有节点类型都具有所有这些属性。例如,文本节点、CDATA 部件、注释、处理指令、属性、空格、文档类型和 XML 声明具有值。而其它节点类型(最重要的是元素和文档)则没有值。通常,程序将使用 nodeType 属性来断定它所查找的内容,然后做出适当的响应。清单 3 展示了简单的 while 循环,该循环使用这些函数来打印它所查看的内容。清单 4 展示了将清单 1 输入程序后的输出。

清单 3. 解析器所查看的内容

while ($reader->read()) {
echo $reader->name;
if ($reader->hasValue) {
echo ": " . $reader->value;
}
echo "n";
}

清单 4. 清单 3 的输出

methodCall
#text:

methodName
#text: sqrt
methodName
#text:

params
#text:

param
#text:

value
double
#text: 10
double
value
#text:

param
#text:

params
#text:

methodCall

大多数程序并非这么简单。它们接受特定格式的输入,并以某种方式来处理输入。在 XML-RPC 例子中,仅需要读取输入中的一个元素:double 元素,该元素应该只有一个。为此,查找名称为 double 的元素的起点:

if ($reader->name == "double" 
&& $reader->nodeType == XMLReader::ELEMENT) {
// ...
}

该元素可能有单个文本子节点,可以通过将解析器前进到下一个节点来进行读取,如下所示:

if ($reader->name == "double" && $reader->nodeType == XMLReader::ELEMENT) {
$reader->read();
respond($reader->value);
}

在这里 respond() 函数构建了 XML-RPC 响应并将它发送到客户机。但是,在展示上述操作前,还有一些事情需要处理。不能绝对保证请求文档中的 double 元素仅包含一个文本节点。可能包含多个文本节点,以及注释和处理指令。例如,可能看起来像以下代码:

<value><double>
<!--value follows-->6.<!--fractional part next-->0
</double></value>

嵌套元素

该模式存在一个潜在的缺陷。嵌套的 double 元素(例如 <double>6<double>1.2</double></double>) 将违背该算法。然而它将成为无效的 XML-RPC;并且不久您将看到如何使用 RELAX NG 验证来拒绝所有此类文档。在诸如可扩展超文本标记语言(Extensible Hypertext Markup Language,XHTML)之类的文档类型中,允许相同元素互相包含(例如 table 元素包含在另一个 table 元素中),因此您还需要知道元素的深度,从而确保结束标记与开始标记之间进行正确匹配。

一个健壮的解决方案需要获得 double 元素的所有文本子节点,将它们连接起来,并且仅将结果转换为 double。必须小心避免任何注释或可能出现的其它非文本节点。这有一点复杂,但并不是十分复杂,如清单 5 所示。

清单 5. 累积来自一个元素的所有文本内容

while ($reader->read()) {
if ($reader->nodeType == XMLReader::TEXT
|| $reader->nodeType == XMLReader::CDATA
|| $reader->nodeType == XMLReader::WHITESPACE
|| $reader->nodeType == XMLReader::SIGNIFICANT_WHITESPACE) {
$input .= $reader->value;
}
else if ($reader->nodeType == XMLReader::END_ELEMENT
&& $reader->name == "double") {
break;
}
}

您可以暂时忽略文档中的其它任何内容。(稍后我将添加更多的错误处理。)

构建响应

正如它的名称所暗示的,XMLReader 仅仅用于读取。相应的 XMLWriter 类正在开发中,但还不能投入到生产。幸运的是,写入 XML 比读取 XML 要容易得多。首先,应使用 header() 函数来设置响应的媒体类型。对于 XML-RPC 来说,媒体类型是 application/xml。例如:

header('Content-type: application/xml');

通常直接将内容显示在页面上,如清单 6 中的 respond() 函数所示。

清单 6. Echo XML

function respond($input) {

echo "<?xml version='1.0'?>
<methodResponse>
<params>
<param>
<value><double>" .
sqrt($input)
. "</double></value>
</param>
</params>
</methodResponse>";

}

甚至可以将响应的文字部分直接嵌入 PHP 页面中,就像使用 HTML 时一样。清单 7 展示了该技术。

清单 7. 文字表示的 XML

function respond($input) {

?><?xml version='1.0'?>
<methodResponse>
<params>
<param>
<value><double>"<?php
echo sqrt($input);
?>
</double></value>
</param>
</params>
</methodResponse>
<?php
}

错误处理

到现在为止,一直隐含假定输入文档是格式规范的文档。但是不能保证情况都是如此。像任何 XML 解析器一样,只要发现一个规范格式错误,XMLReader 就必须停止处理。如果是这样的话,read() 函数将返回 false。

从理论上讲,解析器将报告数据直到发现第一个错误。但是在对小型文档进行试验时,几乎是立刻显示错误信息。底层解析器将预解析大块文档,对它进行缓存,然 后每次分发出一小块文档。因此往往会过早地检查错误。出于安全考虑,不要假定在发现第一个规范格式错误之前能够解析内容。此外,也不要假设解析错误出现之 前看不到任何内容。如果希望只接受完整的、格式规范的文档,那么请确保在看到文档终点之前脚本不能进行任何不可逆操作。

如果解析器检测到规范格式错误,那么 read() 函数将显示如下错误消息(如果启用了详细错误报告,且位于开发服务器上时):

<br />
<b>Warning</b>: XMLReader::read() [<a href='function.read'>function.read</a>]:
< value><double>10</double></value> in <b>/var/www/root.php</b>
on line <b>35</b><br />

您可能不希望将它复制到用户所看到的 HTML 页面中。更好的方法是在 $php_errormsg 环境变量中捕获错误消息。为此,需要启用 php.ini 文件中的 track_errors 配置选项:

track_errors = On

默认情况下,track_errors 选项是关闭的;这在 php.ini 中是显式指定的,因此请确保更改了该行代码。如果提早在 php.ini 中添加了上述一行代码(正如最初我所进行的操作),则后面的 track_errors = Off 代码将重写先前的代码。

该程序仅将响应发送到完整的、格式良好的输入。(也是有效的,不过将实现这点。)因此您需要等待,直到完成了文档的解析(已经跳出 while 循环)。这时,检查是否设置了 $php_errormsg 变量。如果没有进行设置,则文档是格式良好的文档,然后发送 XML-RPC 响应消息。如果设置了该变量,则文档不是格式良好的文档,并发送 XML-RPC 错误响应。如果有人请求负数的平方根,也将发送错误响应。清单 8 展示以上操作。

清单 8. 检查文档格式是否良好


// set up the request
$request = $HTTP_RAW_POST_DATA;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
if (isset($php_errormsg)) unset(($php_errormsg);
// create the reader
$reader = new XMLReader();
// $reader->setRelaxNGSchema("request.rng");
$reader->XML($request);

$input = "";
while ($reader->read()) {
if ($reader->name == "double" && $reader->nodeType == XMLReader::ELEMENT) {

while ($reader->read()) {
if ($reader->nodeType == XMLReader::TEXT
|| $reader->nodeType == XMLReader::CDATA
|| $reader->nodeType == XMLReader::WHITESPACE
|| $reader->nodeType == XMLReader::SIGNIFICANT_WHITESPACE) {
$input .= $reader->value;
}
else if ($reader->nodeType == XMLReader::END_ELEMENT
&& $reader->name == "double") {
break;
}
}
break;
}
}

// make sure the input was well-formed
if (isset($php_errormsg) ) fault(21, $php_errormsg);
else if ($input < 0) fault(20, "Cannot take square root of negative number");
else respond($input);

这是 XML 流处理中简单的常见模式。解析器将填写一个数据结构,当完成文档时该数据结构将起作用。通常数据结构要比文档本身简单。这里所使用的数据结构尤其简单:一个字符串。

验证

libxml 版本

在 libxml 的早期版本中,RELAX NG 有一些严重错误,XMLReader 取决于 libxml 库。请确保所使用的版本至少是 2.06.26 版。很多系统(包括 Mac OS X Tiger)捆绑了较早的、有错误的 libxml 版本。

到目前为止,对于验证数据是否位于所预期的地方,并没有给予关注。实现该验证的最简单的方法是检查文档的模式。XMLReader 支持 RELAX NG 模式语言;清单 9 展示了简单的 RELAX NG 模式,用于这个特定的 XML-RPC 请求表单。

清单 9. XML-RPC 请求

<element name="methodCall" xmlns="http://relaxng.org/ns/structure/1.0" 
datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
<element name="methodName">
<value>sqrt</value>
</element>
<element name="params">
<element name="param">
<element name="value">
<element name="double">
<data type="double"/>
</element>
</element>
</element>
</element>
</element>

可以使用 setRelaxNGSchemaSource() 将模式作为一串文字直接嵌入 PHP 脚本,或者使用 setRelaxNGSchema() 从外部文件或 URL 读取模式。例如,假定清单 9 位于 sqrt.rng 文件中,下面将展示如何载入模式:

reader->setRelaxNGSchema("sqrt.rng")

在开始解析文档 之前,执行上述操作。解析器在进行读取时将检查文档的模式。若要检查文档是否有效,则调用 isValid(),如果文档是有效的(目前为止),则返回 true,否则,返回 false。清单 10 展示了完整的程序,包括所有错误处理。这样将接受任何合法输入,然后返回正确的值,而且将拒绝所有不正确的请求。我还添加了 fault() 方法,当发生故障时将发送 XML-RPC 错误响应。

清单 10. 完整的 XML-RPC 平方根服务器

<?php
header('Content-type: application/xml');

// try grammar
$schema = "<element name='methodCall'
xmlns='http://relaxng.org/ns/structure/1.0'
datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'>
<element name='methodName'>
<value>sqrt</value>
</element>
<element name='params'>
<element name='param'>
<element name='value'>
<element name='double'>
<data type='double'/>
</element>
</element>
</element>
</element>
</element>";


if (!isset($HTTP_RAW_POST_DATA)) {
fault(22, "Please make sure always_populate_raw_post_data = On in php.ini");
}
else {

// set up the request
$request = $HTTP_RAW_POST_DATA;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// create the reader
$reader = new XMLReader();
$reader->setRelaxNGSchema("request.rng");
$reader->XML($request);

$input = "";
while ($reader->read()) {
if ($reader->name == "double" && $reader->nodeType == XMLReader::ELEMENT) {

while ($reader->read()) {
if ($reader->nodeType == XMLReader::TEXT
|| $reader->nodeType == XMLReader::CDATA
|| $reader->nodeType == XMLReader::WHITESPACE
|| $reader->nodeType == XMLReader::SIGNIFICANT_WHITESPACE) {
$input .= $reader->value;
}
else if ($reader->nodeType == XMLReader::END_ELEMENT
&& $reader->name == "double") {
break;
}
}
break;
}
}

if (isset($php_errormsg) ) fault(21, $php_errormsg);
else if (! $reader->isValid()) fault(19, "Invalid request");
else if ($input < 0) fault(20, "Cannot take square root of negative number");
else respond($input);

$reader->close();
}


function respond($input)
{
?>
<methodResponse>
<params>
<param>
<value><double><?php
echo sqrt($input);
?></double></value>
</param>
</params>
</methodResponse>
<?php
}


function fault($code, $message)
{

echo "<?xml version='1.0'?>
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>" . $code . "</int></value>
</member>
<member>
<name>faultString</name>
<value>
<string>" . $message . "</string>
</value>
</member>
</struct>
</value>
</fault>
</methodResponse>";

}

属性

在正常的推解析期间不会看到属性。若要读取属性,请停止在元素的起点处,通过名称或编号来请求特定属性。

将需要的属性名称传递到 getAttribute(),以便在当前元素上查找该属性的值。例如,下面的语句请求当前元素的 id 属性:

$id = $reader->getAttribute("id");

如果属性位于名称空间中 —— 例如,xlink:href —— 则调用 getAttributeNS(),将本地名称和名称空间 URI 分别作为第一个和第二个参数进行传递。(前缀是无关紧要的。)例如,下面的语句将请求 http://www.w3.org/1999/xlink/ 名称空间中 xlink:href 属性的值:

$href = $reader->getAttributeNS("href", "http://www.w3.org/1999/xlink/");

如果属性不存在,那么这两种方法都将返回空字符串。(这是不正确的。它们应该返回 null。当前设计很难区分值为空字符串的属性和值根本不存在的属性。)

属性次序

在 XML 文档中,属性次序并不重要,并且不受解析器的保护。这里用于属性索引的编号仅仅是为了方便起见。不能保证开始标记中的第一个属性就是属性 1,第二个就是属性 2 等等。不要编写依赖于属性次序的代码。

如果仅希望了解元素上的所有属性,并且事先并不知道属性名,那么当读取器位于元素上时,调用 moveToNextAttribute()。一旦解析器位于属性节点上,就可以读取属性的名称、名称空间以及元素所使用的相同属性的值。例如,以下代码片段将打印当前元素的所有属性:

if ($reader->hasAttributes and $reader->nodeType == XMLReader::ELEMENT) {
while ($reader->moveToNextAttribute()) {
echo $reader->name . "='" . $reader->value . "'n";
}
echo "n";
}

对于 XML API 来说非常难得的是,XMLReader 允许从元素的起点 或终点 读取属性。为了避免重复计算,确认代码类型是 XMLReader::ELEMENT 而不是 XMLReader::END_ELEMENT 是很重要的,后者也可能拥有属性。

结束语

XMLReader 是添加到 PHP 程序员工具箱中的一个很有用的工具。与 SimpleXML 不同,它是处理所有文档(而不是部分文档)的完整 XML 解析器。与 DOM 不同,它可以处理大于可用内存的文档。与 SAX 不同,它将程序置于控制之下。如果 PHP 程序需要接受 XML 输入,则 XMLReader 是很值得考虑的一个工具。

参考资料
学习

    * 您可以参阅本文在 developerWorks 全球网站上的 英文原文。

    * XMLReader 的官方文档:阅读 PHP 5 手册。

    * PHP XMLReader 类:阅读有关 libxml 的 C XMLReader API 之上的这个薄层的更多内容。

    * .NET 的 Ajax System.Xml.XmlTextReader:查看该 API 的灵感。

    * XML in a Nutshell(Elliotte Rusty Harold 和 W. Scott Means,O’Reilly,2005):在这本小而全面的书籍中深入研究了 XML —— 可以作为全面介绍和参考资料。

    * Java 编程中的 XML-RPC(Roy Miller,developerWorks,2004 年 1 月):为应用程序间通信的最简路径编写的 XML-RPC 客户机和服务器。

    * PHP 中的 SimpleXML 处理(Elliotte Rusty Harold,developerWorks,2006 年 10 月):使用 SimpleXML 扩展,在 PHP 中使用 SimpleXML 编写特定于标记的 RSS 阅读器。

    * 使用 RELAX NG 反击,第 1 部分(David Mertz,developerWorks,2003 年 2 月):使用 RELAX NG 来创建强大的、简练的、语义简单易懂的类,用于描述有效 XML 实例。

    * Design Patterns(Addison-Wesley,1995 年):深入研究 Gang of Four 的力作中对 Observer 和 Iterator 设计模式的阐述。

    * IBM XML 认证:了解如何才能成为一名 IBM 认证的 XML 及相关技术的开发人员。

    * XML 技术库:查看 developerWorks 中国网站 XML 专区,获得大量技术文章、技巧、教程、标准以及 IBM 红皮书。

    * developerWorks 技术活动和网络广播:随时关注这些会议中的技术进展。

获得产品和技术

    * 使用 IBM 试用版软件:构建您的下一个开发项目,可直接从 developerWorks 下载。

讨论

    * XML 专区讨论论坛:参与任何一个面向 XML 的论坛。

    * 通过参与 developerWorks blogs 加入 developerWorks 社区。

关于作者

Photo of Elliot Rusty Harold       

Elliotte Harold 出生在新奥尔良,现在他还定期回老家喝一碗美味的秋葵汤。但目前他和妻子 Beth、他们的狗 Shayna、猫 Charm 和 Marjorie 定居在布鲁克林附近的 Prospect Heights。他是 Polytechnic 大学的计算机科学副教授,讲授 Java 和面向对象编程。他的 Cafe au Lait Web 站点是 Internet 上最受欢迎的独立 Java 站点之一,子站点 Cafe con Leche 是最受欢迎的 XML 站点之一。他的著作包括 Effective XML、 Processing XML with Java、 Java Network Programming 和 The XML 1.1 Bible。他的最新著作是 Java I/O, 第二版。他目前从事 XOM API 处理 XML、Jaxen XPath 引擎和 Jester 测试覆盖工具的研究。