Hongmu Notes
Home Language Notes PHP gets Baidu drop-down words
Language Notes PHP

PHP gets Baidu drop-down words

PHP gets Baidu drop-down words

Sometimes when doing SEO, you want to use a program to automatically modify the title. At this time, you can use the Baidu drop-down dictionary to automatically match the modification. The following is a PHP code to obtain the Baidu dictionary.

//获取百度下拉信息
$title = urlencode($data['title']);
$api = "https://www.baidu.com/sugrec?pre=1&p=1&ie=utf-8&prod=pc&csor=2&wd=".$title."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
$r = json_decode($r,true);

if(empty($r['g'])){
$new_title = $data['title'].'(图文)';
}

//数据一定存在,取出数据,然后随机获取一个
$baidu_title = $r['g'][mt_rand(0,count($r['g'])-1)]['q'];//数据的随机获取
$baidu_title2 = $r['g'][mt_rand(0,count($r['g'])-1)]['q'];//数据的随机获取
$baidu_title = $baidu_title==$data['title']?$r['g'][mt_rand(0,count($r['g'])-1)]['q']:$baidu_title;//数据随机,防止与原标题一样
$baidu_title2 = $baidu_title==$baidu_title2?$r['g'][mt_rand(0,count($r['g'])-1)]['q']:$baidu_title2;//数据随机,防止与第一个百度标题一样

Optimized code:

<?php
// 获取百度下拉信息
$title = urlencode($data['title']);
$api = "https://www.baidu.com/sugrec?pre=1&p=1&ie=utf-8&prod=pc&csor=2&wd=".$title."";

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $api,
    CURLOPT_TIMEOUT => 5,
    CURLOPT_RETURNTRANSFER => true,
]);

$r = curl_exec($ch);
curl_close($ch);

$r = json_decode($r, true);

// 检查是否为空,如果为空,则添加后缀到标题中
if (empty($r['g'])) {
    $new_title = $data['title'] . ' (图文)';
}

// 从建议中获取随机标题
$titles = array_column($r['g'], 'q');
$random_title = $titles[array_rand($titles)];

// 避免与原始标题和先前的建议重复
if ($random_title == $data['title'] || $random_title == $baidu_title) {
    $random_title = $titles[array_rand($titles)];
}

$baidu_title = $random_title;
$baidu_title2 = $titles[array_rand($titles)];

if ($baidu_title2 == $baidu_title) {
    $baidu_title2 = $titles[array_rand($titles)];
}

Code improvements include:

  • Use an array to store random header options to avoid duplication
  • Use array_column Extract headers from response
  • Use array_rand Get random title from options array
  • Simplified to avoid duplication of code with original title and previous suggestions
  • Set curl options using array arguments to improve readability and maintainability

According to the above code, it is encapsulated into a function. After passing in the Chinese title, if the drop-down is successfully obtained, the drop-down array will be returned. If the acquisition is empty, false will be returned.

function getBaiduSuggestion($title) {
    $title = urlencode($title);
    $api = "https://www.baidu.com/sugrec?pre=1&p=1&ie=utf-8&prod=pc&csor=2&wd=".$title."";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $api,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_RETURNTRANSFER => true,
    ]);

    $r = curl_exec($ch);
    curl_close($ch);

    $r = json_decode($r, true);

    if (!empty($r['g'])) {
        $titles = array_column($r['g'], 'q');
        $baidu_title = $titles[array_rand($titles)];

        if ($baidu_title == $title) {
            $baidu_title = $titles[array_rand($titles)];
        }

        $baidu_title2 = $titles[array_rand($titles)];

        if ($baidu_title2 == $baidu_title) {
            $baidu_title2 = $titles[array_rand($titles)];
        }

        return [$baidu_title, $baidu_title2];
    } else {
        return false;
    }
}

Change the code according to your needs:

function getBaiduSuggestion($title) {
    $title = urlencode($title);
    $api = "https://www.baidu.com/sugrec?pre=1&p=1&ie=utf-8&prod=pc&csor=2&wd=".$title."";

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $api,
        CURLOPT_TIMEOUT => 5,
        CURLOPT_RETURNTRANSFER => true,
    ]);

    $r = curl_exec($ch);
    curl_close($ch);

    $r = json_decode($r, true);

    if (!empty($r['g'])) {
        return array_column($r['g'], 'q');
    } else {
        return false;
    }
}
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 143
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 191
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Responsive Essay Writing Sample Website Template 0781

Responsive Essay Writing Sample Website Template 0781 Practical Collection Yiyou template

An EyouCMS responsive website template designed for essay writing and work sample documents. Its clean and practical design enables users to access a variety of sample essays, work templates, writing materials, and downloadable resources. This template helps educational content platforms attract both students and professionals online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (E...
👁 57
Social and民生新闻博客网站模板 0782

Social and民生新闻博客网站模板 0782 Practical Collection Yiyou template

This EyouCMS template is ideal for social affairs and news blog websites, featuring a feed-based design that aggregates trending social topics, public affairs updates, in-depth reports, and commentary articles. It helps news media attract online readers and build social influence. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Ey...
👁 62
News Blog & Information Website Template 0783

News Blog & Information Website Template 0783 Practical Collection Yiyou template

An EyouCMS template designed for news, blog, and information websites. It features a modern information-flow design, making it ideal for aggregating industry news, in-depth reports, commentary articles, and trending topics. This template helps information websites attract readers online and build media influence. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (E...
👁 54
Resource website typecho001 template

Resource website typecho001 template Program Notes Typecho

typecho001 template template please do not modify the folder name of this template. The folder name is: typecho001 1.4 Fix the js output problem on the article page 1.3 Fix the error prompt when the plug-in is not installed Optimize the list page code output 1.2 Fix the comment function and add a custom homepage title 1.1 Fix the comment reply asymmetry function Add a separate title setting function on the homepage Add the website favicon.ico icon Add one...
👁 199
General Knowledge News Blog Information Website Template 0784

General Knowledge News Blog Information Website Template 0784 Practical Collection Yiyou template

This EyouCMS template is ideal for lifestyle and news blog websites featuring a fresh, information-flow design, making it perfect for sharing lifestyle guides, health tips, practical tricks, and trending news. It helps lifestyle information platforms attract readers online. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Eyou...
👁 31
Modification of typecho paging style

Modification of typecho paging style Program Notes Typecho

Sir, times have changed! Typecho is currently the most perfect solution, because Baidu can only see the code of fixed thinking. The actual generated HTML code is breathtakingly clean and fully customized, including adding classes to the li element, adding classes to the a element, adding classes to the previous page and next page, and removing the li tags that come with typecho to express more. I can even add some text to the content inside...
👁 517