search
HomeBackend DevelopmentPHP TutorialWeChat public platform development (67) Baidu Encyclopedia_PHP tutorial

WeChat public platform development (67) Baidu Encyclopedia_PHP tutorial

Jul 20, 2016 am 11:16 AM
httpenterpriseauthoraddressstudioplatformdevelopWeChatmodelBaiduEncyclopedia

WeChat public platform development WeChat public platform development model Enterprise WeChat public platform Baidu Encyclopedia
Author: Fangbei Studio
Address: http://www.cnblogs.com/txw1958/p/weixin67-baike.html

Baidu Encyclopedia is an open and free online encyclopedia, aiming to create a Chinese knowledge encyclopedia covering all fields of knowledge and serving all Internet users. Based on the Internet spirit of equality, collaboration, sharing, and freedom, Baidu Encyclopedia advocates that everyone is equal before the Internet, and everyone collaborates to write the encyclopedia, so that knowledge can be continuously combined and expanded under certain technical rules and cultural context.

Baidu Encyclopedia

Provide users with a creative network platform, emphasize user participation and dedication, fully mobilize the power of all Internet users, bring together the brains and wisdom of hundreds of millions of users, actively communicate and share, and at the same time achieve perfect integration with search engines, from various different Satisfy users’ information needs at different levels. What Baidu Encyclopedia provides is a platform where all Internet users can equally browse, create, and improve content. All Chinese Internet users can find the comprehensive, accurate and objective definitional information they want on Baidu Encyclopedia

Grab content from Baidu Encyclopedia

<?<span php

</span><span //</span><span echo getbaike('马化腾'); //输出 http://baike.baidu.com/view/1466380.htm</span>

<span function</span> getEncyclopediaInfo(<span $name</span><span ){
    </span><span $name_gbk</span> = <span iconv</span>('utf-8', 'gbk', <span $name</span>); <span //</span><span 将字符转换成GBK编码,若文件为GBK编码可去掉本行</span>
    <span $encode</span> = <span urlencode</span>(<span $name_gbk</span>); <span //</span><span 对字符进行URL编码</span>
    <span $url</span> = 'http://baike.baidu.com/list-php/dispose/searchword.php?word=' .<span $encode</span>. '&pic=1'<span ;
    </span><span $get_contents</span> = httpGetRequest_baike(<span $url</span>); <span //</span><span 获取跳转页内容</span>
    <span $get_contents_gbk</span> = <span iconv</span>('gbk', 'utf-8', <span $get_contents</span>); <span //</span><span 将获取的网页转换成UTF-8编码,若文件为GBK编码可去掉本行</span>
    <span preg_match</span>("/URL=(\S+)'>/s", <span $get_contents_gbk</span>, <span $out</span>); <span //</span><span 获取跳转后URL</span>
    <span $real_link</span> = 'http://baike.baidu.com' .<span $out</span>[1<span ];

    </span><span $get_contents2</span> = httpGetRequest_baike(<span $real_link</span>); <span //</span><span 获取跳转页内容</span>
    <span preg_match</span>('#"Description"\scontent="(.+?)"\s\/\>#is', <span $get_contents2</span>, <span $matchresult</span><span );
    </span><span if</span> (<span isset</span>(<span $matchresult</span>[1]) && <span $matchresult</span>[1] != ""<span ){
        </span><span return</span> <span $matchresult</span>[1<span ];
    }</span><span else</span><span {
        </span><span return</span> "抱歉,没有找到与&ldquo;".<span $name</span>."&rdquo;相关的百科结果。"<span ;
    }
}


</span><span function</span> httpGetRequest_baike(<span $url</span><span )
{
    </span><span $headers</span> = <span array</span><span (
        </span>"User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1",
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language: en-us,en;q=0.5",
        "Referer: http://www.baidu.com/"<span 
    );
    </span><span $ch</span> =<span  curl_init();
    curl_setopt(</span><span $ch</span>, CURLOPT_URL, <span $url</span><span );
    curl_setopt(</span><span $ch</span>, CURLOPT_RETURNTRANSFER, 1<span );
    curl_setopt(</span><span $ch</span>, CURLOPT_HTTPHEADER, <span $headers</span><span );
    </span><span $output</span> = curl_exec(<span $ch</span><span );
    curl_close(</span><span $ch</span><span );

    </span><span if</span> (<span $output</span> === <span FALSE</span><span ){
        </span><span return</span> "cURL Error: ". curl_error(<span $ch</span><span );
    }
    </span><span return</span> <span $output</span><span ;
}
</span>?>

Call in WeChat

<?<span php

</span><span define</span>("TOKEN", "weixin"<span );

</span><span $wechatObj</span> = <span new</span><span  wechatCallbackapiTest();
</span><span $wechatObj</span>-><span responseMsg();

</span><span class</span><span  wechatCallbackapiTest
{
    </span><span public</span> <span function</span><span  valid()
    {
        </span><span $echoStr</span> = <span $_GET</span>["echostr"<span ];
        </span><span //</span><span valid signature , option</span>
        <span if</span>(<span $this</span>-><span checkSignature()){
            </span><span echo</span> <span $echoStr</span><span ;
            </span><span exit</span><span ;
        }
    }

    </span><span private</span> <span function</span><span  checkSignature()
    {
        </span><span $signature</span> = <span $_GET</span>["signature"<span ];
        </span><span $timestamp</span> = <span $_GET</span>["timestamp"<span ];
        </span><span $nonce</span> = <span $_GET</span>["nonce"<span ];

        </span><span $token</span> =<span  TOKEN;
        </span><span $tmpArr</span> = <span array</span>(<span $token</span>, <span $timestamp</span>, <span $nonce</span><span );
        </span><span sort</span>(<span $tmpArr</span><span );
        </span><span $tmpStr</span> = <span implode</span>( <span $tmpArr</span><span  );
        </span><span $tmpStr</span> = <span sha1</span>( <span $tmpStr</span><span  );

        </span><span if</span>( <span $tmpStr</span> == <span $signature</span><span  ){
            </span><span return</span> <span true</span><span ;
        }</span><span else</span><span {
            </span><span return</span> <span false</span><span ;
        }
    }

    </span><span public</span> <span function</span><span  responseMsg()
    {
        </span><span //</span><span get post data, May be due to the different environments</span>
        <span $postStr</span> = <span $GLOBALS</span>["HTTP_RAW_POST_DATA"<span ];
        logger(</span>"R ".<span $postStr</span><span );
        </span><span //</span><span extract post data</span>
        <span if</span> (!<span empty</span>(<span $postStr</span><span )){
            </span><span $postObj</span> = <span simplexml_load_string</span>(<span $postStr</span>, 'SimpleXMLElement',<span  LIBXML_NOCDATA);
            </span><span $RX_TYPE</span> = <span trim</span>(<span $postObj</span>-><span MsgType);

            </span><span switch</span> (<span $RX_TYPE</span><span )
            {
                </span><span case</span> "text":
                    <span $resultStr</span> = <span $this</span>->receiveText(<span $postObj</span><span );
                    </span><span break</span><span ;
                </span><span case</span> "event":
                    <span $resultStr</span> = <span $this</span>->receiveEvent(<span $postObj</span><span );
                    </span><span break</span><span ;
                </span><span default</span>:
                    <span $resultStr</span> = "unknow msg type: ".<span $RX_TYPE</span><span ;
                    </span><span break</span><span ;
            }
            logger(</span>"T ".<span $resultStr</span><span );
            </span><span echo</span> <span $resultStr</span><span ;
        }</span><span else</span><span  {
            </span><span echo</span> ""<span ;
            </span><span exit</span><span ;
        }
    }

    </span><span private</span> <span function</span> receiveText(<span $object</span><span )
    {
        </span><span $funcFlag</span> = 0<span ;
        </span><span $keyword</span> = <span trim</span>(<span $object</span>-><span Content);
        </span><span $resultStr</span> = ""<span ;
        </span><span $contentStr</span> = ""<span ;

        </span><span include</span>('baike.php'<span );
        </span><span $contentStr</span> = getEncyclopediaInfo(<span $keyword</span><span );
        </span><span $resultStr</span> = <span $this</span>->transmitText(<span $object</span>, <span $contentStr</span>, <span $funcFlag</span><span );
        </span><span return</span> <span $resultStr</span><span ;
    }

    </span><span private</span> <span function</span> receiveEvent(<span $object</span><span )
    {
        </span><span $contentStr</span> = ""<span ;
        </span><span switch</span> (<span $object</span>-><span Event)
        {
            </span><span case</span> "subscribe":
                <span $contentStr</span> = "欢迎关注"<span ;
        }
        </span><span $resultStr</span> = <span $this</span>->transmitText(<span $object</span>, <span $contentStr</span><span );
        </span><span return</span> <span $resultStr</span><span ;
    }

    </span><span private</span> <span function</span> transmitText(<span $object</span>, <span $content</span>, <span $flag</span> = 0<span )
    {
        </span><span $textTpl</span> = "<span <xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%d</FuncFlag>
</xml></span>"<span ;
        </span><span $resultStr</span> = <span sprintf</span>(<span $textTpl</span>, <span $object</span>->FromUserName, <span $object</span>->ToUserName, <span time</span>(), <span $content</span>, <span $flag</span><span );
        </span><span return</span> <span $resultStr</span><span ;
    }

}

</span><span function</span> logger(<span $log_content</span><span )
{

}
</span>?>


Welcome to follow Fangbei Studio on WeChat to experience the functions we have developed and understand the latest trends in the industry

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440099.htmlTechArticleWeChat public platform development WeChat public platform development model Enterprise WeChat public platform Baidu Encyclopedia Author: Fangbei Studio Address: http ://www.cnblogs.com/txw1958/p/weixin67-baike.html...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),