Hongmu Notes
Home Program Notes Yiyou cms php remotely obtains article data and publishes articles regularly
Program Notes Yiyoucms

Yiyou cms php remotely obtains article data and publishes articles regularly

Yiyou cms php remotely obtains article data and publishes articles regularly

PHP remotely obtains article data and then publishes it to your own website!

20231127221115108-图片

 

Comes with optimized double titles

Comes with keyword segmentation

Automatically insert pictures into articles

Comes with tag aggregation

Automatically update homepage cache

Automatic updates can be achieved in conjunction with the Pagoda scheduled tasks

Code:

 隐藏内容:评论后查看
<?php
// token验证
$token = md5('你的密钥');
// echo $token;
if($_GET['token']  !== $token){
    echo '非法请求';
    die();
}
// 获取远程数据
$api = get_api('https://你的接口/e/api/juzi.php?token='.$token);
if(empty($api)){
    echo json_encode(['code'=>'404','message'=>'发布失败,获取内容为空!']);die();
}

// 匹配双标题
$api2 = getBaiduSuggestion($api['data']['title']);
if(!empty($api2)){
    $api['data']['title'] .= "($api2)";
}
// 关键词
$api3 = get_api("http://py.4s5.cn/jieba?title=".urlencode($api['data']['title']));
$keywords = '';
if(!empty($api3)){
    $keywords = implode(',',$api3);
}

$api['data']['content'] = insertImage($api['data']['content']);
// echo $api['data']['content'];die;

// 定义数据库连接的参数
$database = require('../application/database.php');

// 创建数据库连接
$connection = mysqli_connect($database['hostname'], $database['username'], $database['password'], $database['database']);

// 检查连接是否成功
if (!$connection) {
    die("数据库连接失败: " . mysqli_connect_error());
}

// 设置字符集
mysqli_set_charset($connection, "utf8");
// 查询数据库中的数据
$sqlQuery = "SELECT * FROM `ey_arctype` WHERE `tempview` != ' ' AND `is_part` = 0 AND `is_del` = 0";
$result = mysqli_query($connection, $sqlQuery);

if (mysqli_num_rows($result) > 0) {
  // 输出数据
  while ($row = mysqli_fetch_assoc($result)) {
      $typeid[] =$row['id']; 
  }
} else {
  die('栏目不存在!');
}

        
// 构建文章数据数组
$data = [
    'typeid' => $typeid[mt_rand(0,(count($typeid)-1))],
    'channel' => '1',
    'title' => $api['data']['title'],
    'litpic' => '/uploads/allimg/20241010/'.md5(mt_rand(1,106)).'.jpg',
    'seo_keywords' => $keywords,
    'seo_description' => mb_substr(strip_tags($api['data']['content']), 0, 160, 'utf-8'),
    'attrlist_id' => 0,
    'sort_order' => time(),
    'add_time' => time(),
    'update_time' => time()
];

// 构建文章内容数据数组
$contentData = [
    'content' => $api['data']['content'],
    'add_time' => time(),
    'update_time' => time()
];
// 设置数据主表的文章数据
$query = "INSERT INTO `ey_archives` (`aid`, `typeid`, `channel`, `title`, `litpic`, `seo_keywords`, `seo_description`, `attrlist_id`, `sort_order`, `add_time`, `update_time`) VALUES (NULL, '{$data['typeid']}', '{$data['channel']}', '{$data['title']}', '{$data['litpic']}', '{$data['seo_keywords']}', '{$data['seo_description']}', '{$data['attrlist_id']}', '{$data['sort_order']}', '{$data['add_time']}', '{$data['update_time']}')";

// 执行插入操作,并获取插入成功的id
$result = mysqli_query($connection, $query);
if ($result) {
    $insertedId = mysqli_insert_id($connection);

    // 设置数据副表的文章数据
    $contentQuery = "INSERT INTO `ey_article_content` (`id`, `aid`, `content`, `add_time`, `update_time`) VALUES (NULL, '$insertedId', '{$contentData['content']}', '{$contentData['add_time']}', '{$contentData['update_time']}')";

    // 执行插入操作
    $contentResult = mysqli_query($connection, $contentQuery);
    if ($contentResult) {
        // 插入成功
        echo '文章发布成功:'.$api['data']['title'].' 栏目ID:'.$data['typeid'].'<br>';
        //更新tag的关系
        if(!empty($api3)){
            foreach ($api3 as $v) {
                 // 查询tag字段是否存在
                $sql = "SELECT * FROM ey_tagindex WHERE tag = '{$v}'";
                $result2 = $connection->query($sql);
                
                if ($result2->num_rows > 0) {
                    $rt = mysqli_fetch_assoc($result2);
                    // tag字段存在,执行其他操作
                    // echo "tag字段【{$v}】已存在<br>";
                    $tagid = $rt['id'];
                } else {
                    // tag字段不存在,插入新记录
                    $tag = $v; // 要插入的tag值
                
                    // 获取当前时间
                    $addTime = time(); // 当前时间
                
                    // 插入新记录
                    $insertSql = "INSERT INTO `ey_tagindex` (`id`, `tag`, `typeid`,  `count`, `total`, `weekcc`, `monthcc`, `weekup`, `monthup`, `is_common`, `lang`, `add_time`, `update_time`) VALUES (NULL, '$tag', '{$data['typeid']}', '0', '2', '0', '0', '$addTime', '$addTime', '0', 'cn', '$addTime', '$addTime')";
                
                    if ($connection->query($insertSql) === TRUE) {
                        // echo "新TAG已成功插入<br>";
                    } else {
                        echo "<br>插入新TAG失败: " . $connection->error;
                    }
                    $tagid = mysqli_insert_id($connection);
                }
                // 插入tag关系
                $sql = "SELECT * FROM ey_taglist WHERE aid = '{$insertedId}' and tag = '{$v}'";
                $result3 = $connection->query($sql);
                
                if ($result3->num_rows > 0) {
                    $rt = mysqli_fetch_assoc($result3);
                    // tag字段存在,执行其他操作
                    // echo "tag关系【{$v}】已存在<br>";
                } else {
                    // tag关系字段不存在,插入新记录
                    $tag = $v; // 要插入的tag值
                    $updateTime = time(); // 当前时间作为update_time字段的值
                    
                    // 构建插入SQL语句
                    $sql = "INSERT INTO `ey_taglist` (`tid`, `aid`, `typeid`, `tag`, `arcrank`, `lang`, `add_time`, `update_time`) VALUES ('$tagid', '{$insertedId}', '{$data['typeid']}', '$v', '0', 'cn', '$updateTime', '$updateTime') ";
                    
                    // 执行插入操作
                    if ($connection->query($sql) === TRUE) {
                    } else {
                        echo "<br>插入新TAG关系失败: " . $connection->error;
                    }
                }
            }
        }
        
        // 清除缓存
        $cacheDIR= '../data/runtime/html/https/index/';
        // print_r($cacheDIR);
        $files =glob($cacheDIR . '*/*.html');
        if(!empty($files)){
            foreach ($files as $v){
                if(unlink($v)){
                }else{
                    echo "<br>删除缓存文件失败:{$v}";
                }
            }
        }
        
    } else {
        // 插入失败
        echo '插入失败' . mysqli_error($connection) . '<br>';
    }
} else {
    // 插入失败
    echo '插入失败' . mysqli_error($connection) . '<br>';
}
// 关闭数据库连接
mysqli_close($connection);

function get_api($durl, $cache = 0)
{
    // 初始化cURL会话
    $ch = curl_init();

    // 设置cURL选项
    curl_setopt($ch, CURLOPT_URL, $durl);          // 设置请求的URL
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);          // 设置超时时间为5秒
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);   // 将结果通过变量返回,而不是直接输出

    // 获取Referer的主机部分
    $referer_host = parse_url($durl, PHP_URL_SCHEME) . '://' . parse_url($durl, PHP_URL_HOST);
    curl_setopt($ch, CURLOPT_REFERER, $referer_host);  // 设置Referer头,指定来源主机部分

    // 模拟浏览器访问的相关选项
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.9999.999 Safari/537.36');  // 设置User-Agent头,模拟浏览器
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json',
    'Content-Type: application/json; charset=utf-8'
    ));
    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    // 执行请求并获取响应结果
    $r = curl_exec($ch);

    // 关闭cURL会话
    curl_close($ch);

    // 解析JSON格式的响应结果,并返回解析后的数组
    return json_decode($r, true);
}

function getBaiduSuggestion($title) {
    // 如果$title超过7个字符,则截取前7个字符
    if (mb_strlen($title, 'utf-8') > 7) {
        $title = mb_substr($title, 0, 7, 'utf-8');
    }
    $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'])) {
        $suggestions = array_column($r['g'], 'q');
        $randomIndex = array_rand($suggestions);
        return $suggestions[$randomIndex];
    } else {
        return false;
    }
}

function insertImage($content) {
    preg_match_all('/<\/p>/', $content, $matches, PREG_OFFSET_CAPTURE);
   $content = str_replace('<h2>','<h3>',$content);
    $content = str_replace('</h2>','</h3>',$content);
    // 如果存在 </p> 标签
    if (!empty($matches[0])) {
        $count = count($matches[0]); // </p> 标签的数量
        
        // 对每个匹配位置应用回调函数
        $content = preg_replace_callback(
            '/<\/p>/',
            function($match) {
                static $insertCount = 0;
                $insertCount++;
                
                // 每隔五个 </p> 插入一张图片
                if ($insertCount % 5 == 0) {
                    return $match[0] . '<p style="text-align:center"><img src="/uploads/allimg/20241010/'.md5(mt_rand(1,106)).'.jpg"></p>';
                } else {
                    return $match[0];
                }
            },
            $content,
            $count - 1 // 限制替换次数为匹配到的 </p> 标签数量减一
        );
    }

    return $content;
}

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

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

Author homepage View home page →

Related articles

How to quickly modify columns in batches in Yiyou CMS?

How to quickly modify columns in batches in Yiyou CMS? Program Notes Yiyoucms

After downloading the Yiyou template, you will find that there are many columns that need to be modified, but I only want to modify the column name, column description, column keywords, and keep the others unchanged. How to do this? PHP script&lt;?php $filePath = './sort.txt'; // Contains database configuration file $dbSet = require('../application/data…
👁 2349
Yiyoucms batch modification of published articles

Yiyoucms batch modification of published articles Program Notes Yiyoucms

After downloading the Yiyou template, I am used to modifying articles directly, so I wrote a php to batch modify Yiyou articles! Including: article title, article content, article description, article keywords (word segmentation of the title) article tag, article release time, etc.! The published article comes from the self-created API interface of Empire CMS! The interface code is very simple: &lt;?php header("content-type:applicati…
👁 321
Summary of common problems in Yiyou CMS installation

Summary of common problems in Yiyou CMS installation Program Notes Yiyoucms

As an enterprise website building system developed based on PHP+MySQL, EyouCMS often encounters various problems during the actual installation and deployment process due to differences in server environments and improper operating procedures. This article summarizes the 7 most common installation errors and their solutions for your reference. Question 1: The installation error "Please carefully check the database account and password" error phenomenon: During the installation process, it prompts "Database connection failed, please try again..."
👁 72
EyouCMS (EyouCms) system installation tutorial

EyouCMS (EyouCms) system installation tutorial Program Notes Yiyoucms

1. System Overview Eyou Content Management System (EyouCms) is an enterprise-level open source website building system developed based on PHP+MySQL architecture, using ThinkPHP 5.0 as the underlying framework. 2. Environmental requirements Before installing EyouCms, please ensure that the server environment meets the following requirements: Project requirements operating system Linux/Unix/WindowsWeb server Nginx/…
👁 58
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...
👁 197

Recommended reading

Responsive real estate project development website template 0170

Responsive real estate project development website template 0170 Practical Collection Yiyou template

An eyouCMS responsive website template designed for real estate development enterprises. Its modern architectural design effectively showcases property projects, development case studies, planning and design work, as well as the company's capabilities. This template helps real estate developers showcase their brand online and attract potential partners. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eyouCMS...
👁 38
Responsive stone carving sculpture website template 0826

Responsive stone carving sculpture website template 0826 Practical Collection Yiyou template

This EyouCMS responsive template is ideal for the stone carving, sculpture, and statue industries. Its classical artistic design is perfect for showcasing stone carving works, sculptural products, artistic designs, and brand stories. It helps stone carving brands showcase their craftsmanship online and attract collectors as well as landscape architecture clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS...
👁 54
(PC+WAP) Red Hot Pot Franchise Website – pbootCMS Template; Download Restaurant & Food Service Website Source Code – 0080

(PC+WAP) Red Hot Pot Franchise Website – pbootCMS Template; Download Restaurant & Food Service Website Source Code – 0080 Practical Collection pbootcms Template

A PbootCMS red-themed website template designed for the hot pot franchise and food service industries, compatible with both PC and WAP devices. Its appealing design is perfect for showcasing hot pot brands, franchise policies, and store branding. The template includes built-in franchise inquiry and online consultation features, making it an effective tool for fast-track franchise recruitment for restaurant chains. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin...
👁 50
Equipped with a multi-level filtering feature – (Adaptive Mobile Version) – Download a responsive PBootCMS website template for overseas study consultation and education training institutions – 0709

Equipped with a multi-level filtering feature – (Adaptive Mobile Version) – Download a responsive PBootCMS website template for overseas study consultation and education training institutions – 0709 Practical Collection pbootcms Template

A PbootCMS website template featuring a multi-level filtering feature and adaptive design for both desktop and mobile devices, specifically designed for study abroad consultation services and educational training institutions. The responsive design ensures an optimal user experience on both desktop and mobile devices, while the multi-level filtering functionality makes it easy for users to search for study abroad programs or course information. This template is an ideal choice for study abroad agencies or educational institutions looking to enhance user experience and improve conversion rates. Template Display | Installation Instructions | Website Backend: /admin.php | Username: adm...
👁 48
Specialty Snack Shop Franchising Website Template 0171

Specialty Snack Shop Franchising Website Template 0171 Practical Collection Yiyou template

This EyouCMS template is ideal for specialty snack shops and franchise businesses. Its modern and appetizing design effectively showcases the specialty snacks, store branding, franchise policies, and brand story, helping snack chain brands attract franchisees and consumers online. Template Demo | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (Ey...
👁 57
Responsive Waterproofing and Leak Repair Project Website Template – 0827

Responsive Waterproofing and Leak Repair Project Website Template – 0827 Practical Collection Yiyou template

An eyouCMS responsive website template designed specifically for the waterproofing and leak repair industry. Its professional architectural design effectively showcases waterproofing and leak repair projects, construction case studies, technical solutions, and the company's capabilities. This template helps waterproofing companies showcase their brand online and attract both commercial and residential clients. Template Overview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Common Installation Questions for YououCMS...
👁 56