search
HomeBackend DevelopmentPHP TutorialAn explanation of examples of php optimized page output and compatible with search engine robot access

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools