Home  >  Article  >  Backend Development  >  An explanation of examples of php optimized page output and compatible with search engine robot access

An explanation of examples of php optimized page output and compatible with search engine robot access

jacklove
jackloveOriginal
2018-06-20 17:08:062068browse

Use PHP to output the page. If the page has a lot of content, the user needs to wait for all the content of the page to be loaded before they can see the page content. The user experience is not good.

1. Page output optimization method

We can divide the page content into several pieces and load them with asynchronous concurrent requests. When any piece of content is loaded successfully, it will be displayed immediately without Need to wait for other chunks of content to load.
In this way, as long as any piece of content is loaded successfully, the user can see it immediately, improving the user experience.

So you only need to keep the js content in the page, and use ajax to request the api to load the content and display it.

<!-- 分块1 --><p id="result1"></p><script type="text/javascript">$(function() {
  $.get("api.php?id=1", {}, function(ret) {
    $("#result1").html(ret["html"]);
  },"json");
});</script><!-- 分块2 --><p id="result2"></p><script type="text/javascript">$(function() {
  $.get("api.php?id=2", {}, function(ret) {
    $("#result2").html(ret["html"]);
  },"json");
});</script><!-- 分块3 --><p id="result3"></p><script type="text/javascript">$(function() {
  $.get("api.php?id=3", {}, function(ret) {
    $("#result3").html(ret["html"]);
  },"json");
});</script>...

An explanation of examples of php optimized page output and compatible with search engine robot access

Asynchronous and concurrent loading of content can greatly speed up page output.

2. Page output is compatible with search engines

If you use asynchronous concurrent loading to output the page, it is not friendly to search engines and will be collected by search engines. The content is not available because the content is loaded using ajax.

So we need to determine if it is accessed by a search engine robot, then directly output the page content instead of using asynchronous and concurrent output pages.

How to determine whether search engine robots access it

<?php// 判断是否搜索引擎机器人访问function isRobot() { 
    $agent= strtolower(isset($_SERVER[&#39;HTTP_USER_AGENT&#39;])? $_SERVER[&#39;HTTP_USER_AGENT&#39;] : &#39;&#39;); 
    if(!empty($agent)){ 
        $spiderSite= array( 
            "TencentTraveler", 
            "Baiduspider+", 
            "BaiduGame", 
            "Googlebot", 
            "msnbot", 
            "Sosospider+", 
            "Sogou web spider", 
            "ia_archiver", 
            "Yahoo! Slurp", 
            "YoudaoBot", 
            "Yahoo Slurp", 
            "MSNBot", 
            "Java (Often spam bot)", 
            "BaiDuSpider", 
            "Voila", 
            "Yandex bot", 
            "BSpider", 
            "twiceler", 
            "Sogou Spider", 
            "Speedy Spider", 
            "Google AdSense", 
            "Heritrix", 
            "Python-urllib", 
            "Alexa (IA Archiver)", 
            "Ask", 
            "Exabot", 
            "Custo", 
            "OutfoxBot/YodaoBot", 
            "yacy", 
            "SurveyBot", 
            "legs", 
            "lwp-trivial", 
            "Nutch", 
            "StackRambler", 
            "The web archive (IA Archiver)", 
            "Perl tool", 
            "MJ12bot", 
            "Netcraft", 
            "MSIECrawler", 
            "WGet tools", 
            "larbin", 
            "Fish search", 
        ); 
        foreach($spiderSite as $val){ 
            $str = strtolower($val); 
            if(strpos($agent, $str) !== false){ 
                return true; 
            } 
        } 
    }    return false; 
} 
?>


##3. Complete code and test

index.php Used to be accessed

<?phprequire &#39;server.php&#39;;// 获取内容$data1 = getData(1);$data2 = getData(2);$data3 = getData(3);// 调用模版include dirname(__FILE__).&#39;/template.php&#39;;?>

template.php Page template content

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
 <head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <script src="jquery-1.11.0.min.js"></script>
  <title>内容模版</title>
 </head>

 <body>
    <?php echo $data1; ?>
    <?php echo $data2; ?>
    <?php echo $data3; ?>
 </body></html>

server.php Main method to obtain content

<?php//获取数据,正常情况应该读取db,演示只用数组代替function getData($id){

    // 数据
    $data = array(        1 => &#39;很久很久以前,在某个地方,有个很可爱的女孩。不幸的是,她父母双亡,而且家徒四壁,屋里除了一张可供歇息的床以外,就别无长物了。除此之外,她全身上下只剩下身上所穿的衣裳,还有一片好心人施舍给她有面包而已。这个小姑娘,是个心地善良、信心坚定的好女孩。不论境遇有多么凄惨不幸,她仍然深信,慈爱的上帝会默默地庇护着她。&#39;,        2 => &#39;有一天,她只身上原野上去玩。她走着走着,忽然遇到一个衣衫褴褛的男子。他向女孩哀求道:“求求你!施舍一点东西给我这个可伶人吧!我实在是饿得快要受不了了啊!”听到这话,女孩便把自己仅有的那片面包拿出来,说道:“这是上帝的恩 典喔!”说完后, 女孩就继续上路了。走了一会儿,路旁突然出现了一个啼泣不已的男孩。“鸣——我的头好冷呀!就快冻僵了……你能不能施舍一点可以让我挡风的东西啊!”女孩便把自己头上那顶帽子脱了下来, 为男孩戴上。走了不久,她又碰到一个小孩。那孩子没有穿棉背心,冷得直打哆嗦。于是,好心的女孩便把自己的背心送给那个小孩。她继续往前走,突然又遇见另一个小孩。她再次答应对方的乞求,把上衣施舍给他。女孩再往前走,走进森林里。林深日尽,四周一下子变暗了起来。这时,又出现一个可怜的小男孩, 央求女孩把内衣脱给她。这个时候,虔诚又善良的女孩想:“现在天色已经暗下来了,任谁也看不清楚我的模样,就算脱掉内衣,应该无所谓吧!”因此,女孩脱下了内衣,送给乞讨的女孩。&#39;,        3 => &#39;这个时候的女孩,真的是浑身赤裸、再无他物了。忽然间,天上闪烁的星星纷纷坠落,落在女孩的面前。天啊!它们都化成了闪亮耀眼的金币——货真价实的金币!而原先一丝不挂的孩,不知什么时候,竟裹上了一套细致、上等的亚麻衫!于是,这个好心的女孩,把金币捡回家,从此过着富足、快乐的生活。&#39;
    );    $ret = &#39;&#39;;    // 判断是否搜索引擎机器人
    $is_robot = isRobot();    // 搜索引擎机器人访问
    if($is_robot || defined(&#39;FORCE_SYNC_RESPONSE&#39;) && FORCE_SYNC_RESPONSE==true){        $ret .= &#39;<p>&#39;.$data[$id].&#39;</p>&#39;.PHP_EOL;    // 普通用户访问,异步请求
    }else{        $ret = &#39;<p id="result&#39;.$id.&#39;"></p>
        <script type="text/javascript">
        $(function() {
          $.get("api.php?id=&#39;.$id.&#39;", {}, function(ret) {
            $("#result&#39;.$id.&#39;").html(ret["html"]);
          },"json");
        });
        </script>&#39;.PHP_EOL.PHP_EOL;

    }    return $ret;

}// 判断是否搜索引擎机器人访问function isRobot() { 
    $agent= strtolower(isset($_SERVER[&#39;HTTP_USER_AGENT&#39;])? $_SERVER[&#39;HTTP_USER_AGENT&#39;] : &#39;&#39;); 
    if(!empty($agent)){ 
        $spiderSite= array( 
            "TencentTraveler", 
            "Baiduspider+", 
            "BaiduGame", 
            "Googlebot", 
            "msnbot", 
            "Sosospider+", 
            "Sogou web spider", 
            "ia_archiver", 
            "Yahoo! Slurp", 
            "YoudaoBot", 
            "Yahoo Slurp", 
            "MSNBot", 
            "Java (Often spam bot)", 
            "BaiDuSpider", 
            "Voila", 
            "Yandex bot", 
            "BSpider", 
            "twiceler", 
            "Sogou Spider", 
            "Speedy Spider", 
            "Google AdSense", 
            "Heritrix", 
            "Python-urllib", 
            "Alexa (IA Archiver)", 
            "Ask", 
            "Exabot", 
            "Custo", 
            "OutfoxBot/YodaoBot", 
            "yacy", 
            "SurveyBot", 
            "legs", 
            "lwp-trivial", 
            "Nutch", 
            "StackRambler", 
            "The web archive (IA Archiver)", 
            "Perl tool", 
            "MJ12bot", 
            "Netcraft", 
            "MSIECrawler", 
            "WGet tools", 
            "larbin", 
            "Fish search", 
        ); 
        foreach($spiderSite as $val){ 
            $str = strtolower($val); 
            if(strpos($agent, $str) !== false){ 
                return true; 
            } 
        } 
    }    return false; 
} 
?>

api.php API interface used for asynchronous requests

<?phpdefine(&#39;FORCE_SYNC_RESPONSE&#39;, true); // 强制同步输出require &#39;server.php&#39;;// 获取分块内容$id = isset($_GET[&#39;id&#39;])? $_GET[&#39;id&#39;] : 1;$data = getData($id);// 输出header(&#39;content-type:application/json;charset=utf8&#39;);$ret = json_encode(    array(        &#39;html&#39; => $data
    )
);echo $ret;?>


Test normal user access
<?php$url = &#39;http://localhost/index.php&#39;; // 访问index.php$header = array();$data = doCurl($url, array(), $header);echo &#39;<meta http-equiv="content-type" content="text/html;charset=utf-8">&#39;;echo &#39;<xmp>&#39;;echo $data;echo &#39;</xmp>&#39;;/**
 * curl请求
 * @param  String $url     请求地址
 * @param  Array  $data    请求参数
 * @param  Array  $header  请求header
 * @param  Int    $timeout 超时时间
 * @return String
 */function doCurl($url, $data=array(), $header=array(), $timeout=30){  

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);    $response = curl_exec($ch);  

    if($error=curl_error($ch)){  
        die($error);
    }  

    curl_close($ch);  

    return $response;
}  
?>

Output page content

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
 <head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <script src="jquery-1.11.0.min.js"></script>
  <title>内容模版</title>
 </head>

 <body>
    <p id="result1"></p>

        <script type="text/javascript">
        $(function() {
          $.get("api.php?id=1", {}, function(ret) {
            $("#result1").html(ret["html"]);
          },"json");
        });        </script>
    <p id="result2"></p>

        <script type="text/javascript">
        $(function() {
          $.get("api.php?id=2", {}, function(ret) {
            $("#result2").html(ret["html"]);
          },"json");
        });        </script>
    <p id="result3"></p>

        <script type="text/javascript">
        $(function() {
          $.get("api.php?id=3", {}, function(ret) {
            $("#result3").html(ret["html"]);
          },"json");
        });        </script>
 </body></html>

Uses asynchronous concurrent loading to improve page output speed.



Test search engine robot access
<?php$url = &#39;http://localhost/index.php&#39;; // 访问index.php$header = array(    &#39;user-agent: Googlebot&#39; // 加入搜索引擎关键字);$data = doCurl($url, array(), $header);echo &#39;<meta http-equiv="content-type" content="text/html;charset=utf-8">&#39;;echo &#39;<xmp>&#39;;echo $data;echo &#39;</xmp>&#39;;/**
 * curl请求
 * @param  String $url     请求地址
 * @param  Array  $data    请求参数
 * @param  Array  $header  请求header
 * @param  Int    $timeout 超时时间
 * @return String
 */function doCurl($url, $data=array(), $header=array(), $timeout=30){  

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);    $response = curl_exec($ch);  

    if($error=curl_error($ch)){  
        die($error);
    }  

    curl_close($ch);  

    return $response;
}  
?>

Output page content

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
 <head>
  <meta http-equiv="content-type" content="text/html;charset=utf-8">
  <script src="jquery-1.11.0.min.js"></script>
  <title>内容模版</title>
 </head>

 <body>
    <p>很久很久以前,在某个地方,有个很可爱的女孩。不幸的是,她父母双亡,而且家徒四壁,屋里除了一张可供歇息的床以外,就别无长物了。除此之外,她全身上下只剩下身上所穿的衣裳,还有一片好心人施舍给她有面包而已。这个小姑娘,是个心地善良、信心坚定的好女孩。不论境遇有多么凄惨不幸,她仍然深信,慈爱的上帝会默默地庇护着她。</p>
    <p>有一天,她只身上原野上去玩。她走着走着,忽然遇到一个衣衫褴褛的男子。他向女孩哀求道:“求求你!施舍一点东西给我这个可伶人吧!我实在是饿得快要受不了了啊!”听到这话,女孩便把自己仅有的那片面包拿出来,说道:“这是上帝的恩 典喔!”说完后, 女孩就继续上路了。走了一会儿,路旁突然出现了一个啼泣不已的男孩。“鸣——我的头好冷呀!就快冻僵了……你能不能施舍一点可以让我挡风的东西啊!”女孩便把自己头上那顶帽子脱了下来, 为男孩戴上。走了不久,她又碰到一个小孩。那孩子没有穿棉背心,冷得直打哆嗦。于是,好心的女孩便把自己的背心送给那个小孩。她继续往前走,突然又遇见另一个小孩。她再次答应对方的乞求,把上衣施舍给他。女孩再往前走,走进森林里。林深日尽,四周一下子变暗了起来。这时,又出现一个可怜的小男孩, 央求女孩把内衣脱给她。这个时候,虔诚又善良的女孩想:“现在天色已经暗下来了,任谁也看不清楚我的模样,就算脱掉内衣,应该无所谓吧!”因此,女孩脱下了内衣,送给乞讨的女孩。</p>
    <p>这个时候的女孩,真的是浑身赤裸、再无他物了。忽然间,天上闪烁的星星纷纷坠落,落在女孩的面前。天啊!它们都化成了闪亮耀眼的金币——货真价实的金币!而原先一丝不挂的孩,不知什么时候,竟裹上了一套细致、上等的亚麻衫!于是,这个好心的女孩,把金币捡回家,从此过着富足、快乐的生活。</p>
 </body></html>

The page content is output directly, which is friendly to search engines.

This article explains examples of compatible search engine robot access. For more related content, please pay attention to the PHP Chinese website.

Related recommendations:

Calling ffmpeg through php to obtain video information

Use mysql to determine whether the point is in the specified polygon area Inside

Use imagemagick in php to achieve the old photo effect


The above is the detailed content of An explanation of examples of php optimized page output and compatible with search engine robot access. For more information, please follow other related articles on the PHP Chinese website!

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