


An 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>...
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['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT'] : ''); 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 'server.php';// 获取内容$data1 = getData(1);$data2 = getData(2);$data3 = getData(3);// 调用模版include dirname(__FILE__).'/template.php';?>
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 => '很久很久以前,在某个地方,有个很可爱的女孩。不幸的是,她父母双亡,而且家徒四壁,屋里除了一张可供歇息的床以外,就别无长物了。除此之外,她全身上下只剩下身上所穿的衣裳,还有一片好心人施舍给她有面包而已。这个小姑娘,是个心地善良、信心坚定的好女孩。不论境遇有多么凄惨不幸,她仍然深信,慈爱的上帝会默默地庇护着她。', 2 => '有一天,她只身上原野上去玩。她走着走着,忽然遇到一个衣衫褴褛的男子。他向女孩哀求道:“求求你!施舍一点东西给我这个可伶人吧!我实在是饿得快要受不了了啊!”听到这话,女孩便把自己仅有的那片面包拿出来,说道:“这是上帝的恩 典喔!”说完后, 女孩就继续上路了。走了一会儿,路旁突然出现了一个啼泣不已的男孩。“鸣——我的头好冷呀!就快冻僵了……你能不能施舍一点可以让我挡风的东西啊!”女孩便把自己头上那顶帽子脱了下来, 为男孩戴上。走了不久,她又碰到一个小孩。那孩子没有穿棉背心,冷得直打哆嗦。于是,好心的女孩便把自己的背心送给那个小孩。她继续往前走,突然又遇见另一个小孩。她再次答应对方的乞求,把上衣施舍给他。女孩再往前走,走进森林里。林深日尽,四周一下子变暗了起来。这时,又出现一个可怜的小男孩, 央求女孩把内衣脱给她。这个时候,虔诚又善良的女孩想:“现在天色已经暗下来了,任谁也看不清楚我的模样,就算脱掉内衣,应该无所谓吧!”因此,女孩脱下了内衣,送给乞讨的女孩。', 3 => '这个时候的女孩,真的是浑身赤裸、再无他物了。忽然间,天上闪烁的星星纷纷坠落,落在女孩的面前。天啊!它们都化成了闪亮耀眼的金币——货真价实的金币!而原先一丝不挂的孩,不知什么时候,竟裹上了一套细致、上等的亚麻衫!于是,这个好心的女孩,把金币捡回家,从此过着富足、快乐的生活。' ); $ret = ''; // 判断是否搜索引擎机器人 $is_robot = isRobot(); // 搜索引擎机器人访问 if($is_robot || defined('FORCE_SYNC_RESPONSE') && FORCE_SYNC_RESPONSE==true){ $ret .= '<p>'.$data[$id].'</p>'.PHP_EOL; // 普通用户访问,异步请求 }else{ $ret = '<p id="result'.$id.'"></p> <script type="text/javascript"> $(function() { $.get("api.php?id='.$id.'", {}, function(ret) { $("#result'.$id.'").html(ret["html"]); },"json"); }); </script>'.PHP_EOL.PHP_EOL; } return $ret; }// 判断是否搜索引擎机器人访问function isRobot() { $agent= strtolower(isset($_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT'] : ''); 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('FORCE_SYNC_RESPONSE', true); // 强制同步输出require 'server.php';// 获取分块内容$id = isset($_GET['id'])? $_GET['id'] : 1;$data = getData($id);// 输出header('content-type:application/json;charset=utf8');$ret = json_encode( array( 'html' => $data ) );echo $ret;?>
Test normal user access<?php$url = 'http://localhost/index.php'; // 访问index.php$header = array();$data = doCurl($url, array(), $header);echo '<meta http-equiv="content-type" content="text/html;charset=utf-8">';echo '<xmp>';echo $data;echo '</xmp>';/**
* 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;
}
?>
Copy after login
<?php$url = 'http://localhost/index.php'; // 访问index.php$header = array();$data = doCurl($url, array(), $header);echo '<meta http-equiv="content-type" content="text/html;charset=utf-8">';echo '<xmp>';echo $data;echo '</xmp>';/** * 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>
Test search engine robot access<?php$url = 'http://localhost/index.php'; // 访问index.php$header = array( 'user-agent: Googlebot' // 加入搜索引擎关键字);$data = doCurl($url, array(), $header);echo '<meta http-equiv="content-type" content="text/html;charset=utf-8">';echo '<xmp>';echo $data;echo '</xmp>';/**
* 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;
}
?>
Copy after login
<?php$url = 'http://localhost/index.php'; // 访问index.php$header = array( 'user-agent: Googlebot' // 加入搜索引擎关键字);$data = doCurl($url, array(), $header);echo '<meta http-equiv="content-type" content="text/html;charset=utf-8">';echo '<xmp>';echo $data;echo '</xmp>';/** * 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>
This article explains examples of compatible search engine robot access. For more related content, please pay attention to the PHP Chinese website.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
