Hongmu Notes
Home Program Notes WordPress to EmpireCMS data migration – Category migration code
Program Notes wordpress

WordPress to EmpireCMS data migration – Category migration code

WordPress to EmpireCMS data migration – Category migration code

config.php

 隐藏内容:会员可查看
<?php
define('DB_NAME', 'root');
define('DB_USER', 'root');
define('DB_PASSWORD', 'RspC7M8seHywXZBW');
define('DB_HOST', 'localhost');
define('DB_CHARSET', 'utf8');
// 检测连接
if (!$conn = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD)) {
die("<b>PHP链接MYSQL数据库出现错误!请检查配置!</b>");
}
// //选择数据库
// if(!mysqli_select_db($conn,DB_NAME)){
// die("<b>PHP选择MYSQL数据库出现错误!请检查配置!</b>");
// }
//设置字符集
mysqli_set_charset($conn,DB_CHARSET);

function bq_replac($html){
$html = preg_replace('/{eyou:weapp\s+type=[\s\'"]+default[\s\'"]+\/}/s','',$html);
$html = preg_replace('/{\$eyou.field.typeid\|gettoptype=###,[\s\'"]+typename[\s\'"]+}/','[!--bclass.name--]',$html);
return $html;
}
function str_replace_once($needle, $replace, $haystack) {//只替换一次字符串
$pos = strpos($haystack, $needle);
if ($pos === false) {
return $haystack;
}
return substr_replace($haystack, $replace, $pos, strlen($needle));
}

function turncate($dbname,$dbtable){
global $conn;
if(mysqli_query($conn, "TRUNCATE `{$dbname}`.`{$dbtable}`")){
echo "{$dbname}库{$dbtable}表已清空<br>";
}else{
echo "{$dbname}库{$dbtable}表清空失败<br>";
}
}
function insert_sql($sql){
global $conn;
if(mysqli_query($conn, $sql)){
echo "插入成功<br>";
}else{
echo "插入失败{$sql}<br>";
}
}

function copyDirectory($src, $dst) {
// 检查源目录是否存在并且是否是目录
if (!is_dir($src)) {
return false;
}

// 检查目标目录是否存在并且是否是目录
if (!is_dir($dst)) {
mkdir($dst);
}

// 打开源目录
$dirHandle = opendir($src);

// 循环读取源目录下的文件和目录,复制到目标目录
while (false !== ($file = readdir($dirHandle))) {
if ($file != "." && $file != "..") {
$srcFile = $src . "/" . $file;
$dstFile = $dst . "/" . $file;

if (is_dir($srcFile)) {
copyDirectory($srcFile, $dstFile); // 递归复制子目录
} else {
copy($srcFile, $dstFile);
}
}
}

closedir($dirHandle);

return true;
}

function ToSql($sql){
global $conn;
$r = $conn->query($sql);
if($r){
echo '执行成功:'.$sql.'<br>';
}else{
echo $sql;
}
}
function deleteFiles($dir) {
$files = glob("$dir/*"); // 查找当前目录下的所有文件和目录
foreach($files as $file) {
if(is_file($file)) {
unlink($file); // 删除不需要的文件
} elseif(is_dir($file)) {
deleteFiles($file); // 递归处理子目录
}
}
}
function importSqlZip($remoteUrl, $dbName, $dbUser, $dbPass, $dbHost = 'localhost', $sqlDir = __DIR__.'/path/') {
// 创建一个临时文件用于保存下载的 Zip 文件
$tempZip = tempnam(sys_get_temp_dir(), 'sql_zip_');

// 下载远程 Zip 文件并保存到本地
$fp = fopen($tempZip, 'w');
$ch = curl_init($remoteUrl);
curl_setopt($ch, CURLOPT_FILE, $fp);
$success = curl_exec($ch);
curl_close($ch);
fclose($fp);

if (!$success) {
throw new Exception('Failed to download the remote SQL ZIP file.');
}
// 创建指定目录
if (!mkdir($sqlDir, 0777, true)) {
throw new Exception('Failed to create directory.');
}

// 解压缩文件到指定目录
$zip = new ZipArchive();
if ($zip->open($tempZip) === TRUE) {
$zip->extractTo($sqlDir);
$zip->close();
} else {
throw new Exception('Failed to extract the SQL ZIP file.');
}

$dsn = "mysql:host=$dbHost;dbname=$dbName";
$pdo = new PDO($dsn, $dbUser, $dbPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 获取数据库所有表名
$tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
foreach ($tables as $table) {
// 如果数据表名以指定前缀开头,那么删除该数据表
if (strpos($table, "phome_") === 0) {
$pdo->query("DROP TABLE IF EXISTS $table");
}
}

// 导入 SQL 文件
$files = glob($sqlDir . '*.sql');
foreach ($files as $file) {
$pdo->exec(file_get_contents($file));
}

// 删除临时文件和 SQL 文件
unlink($tempZip);
$files = glob($sqlDir . '*.sql');
foreach ($files as $file) {
unlink($file);
}
rmdir($sqlDir);
}
function file_get($url){
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 设置 User-Agent 头信息
$user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36';
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
// 发送 HTTP 请求
$response = curl_exec($ch);
// 关闭 cURL
curl_close($ch);
// 处理响应结果
if ($response === false) {
return '请求失败';
}
return $response;
}

function match_regex($pattern, $subject) {
if (preg_match($pattern, $subject, $matches)) {
return $matches;
} else {
return false;
}
}

function removeChinese($str) {
return preg_replace('/[\x{4e00}-\x{9fa5}]/u', '', $str);
}

function clearAndImportSQL($dbHost, $dbName, $dbUser, $dbPass, $sqlFile) {
$dbCharset = "utf8mb4";
$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=$dbCharset";

try {
$pdo = new PDO($dsn, $dbUser, $dbPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// 清空数据库表
$tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);

foreach ($tables as $table) {
$pdo->exec("TRUNCATE TABLE $table");
}

// 导入.sql文件
$sql = file_get_contents($sqlFile);

$pdo->exec($sql);

echo "数据库:".$dbName.",SQL文件:{$sqlFile},导入结果:SQL导入成功.<br>";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}

$pdo = null;
}
/**
* 递归更改目录及其子目录和文件的权限
*
* @param string $path 要更改权限的目录路径
* @param int $filemode 文件权限(例如:0644)
* @param int $dirmode 目录权限(例如:0755)
*
* @return bool 成功则返回 true,否则返回 false
*/
function chmod_r($path, $filemode, $dirmode) {
if (is_dir($path) ) {
if (!chmod($path, $dirmode)) { // 更改目录的权限为 dirmode
return false;
}
$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
if($file != '.' && $file != '..') {
$fullpath = $path.'/'.$file;
if(is_link($fullpath)) {
if (!chmod($fullpath, $filemode)) { // 更改符号链接文件的权限为 filemode
return false;
}
} elseif(!is_dir($fullpath)) {
if (!chmod($fullpath, $filemode)) { // 更改普通文件的权限为 filemode
return false;
}
} elseif(!chmod_r($fullpath, $filemode, $dirmode)) { // 递归更改子目录和文件的权限
return false;
}
}
}
closedir($dh);
} else {
if (!chmod($path, $filemode)) { // 更改目录下文件的权限为 filemode
return false;
}
}
return true; // 成功返回 true
}

// 读取数据库文件,然后传入需要替换的数组
function modifyDatabaseConfig($filename, $newConfig) {
// 读取配置文件内容
$file = file_get_contents($filename);
// 替换配置内容

// 配置文件里的变量名前缀
$prefix = '$ecms_config[\'db\']';

// 遍历新配置,将对应的变量替换为新值
foreach ($newConfig as $key => $value) {
$pattern = '/' . preg_quote($prefix) . '\[\'' . preg_quote($key) . '\'\]\s*=\s*\'[^;]+;/';
$replace = $prefix . '[\'' . $key . '\'] = \'' . $value . '\';';
$file = preg_replace($pattern, $replace, $file);
}
// 保存文件
file_put_contents($filename, $file);
}
function find_files($dir, $extension) {
$result = array();
// 打开目录并读取其中的文件
if (is_dir($dir)) {
$files = scandir($dir);
foreach($files as $file) {
if ($file != '.' && $file != '..') {
// 如果是目录,则递归查询子目录
if (is_dir($dir . '/' . $file)) {
$result = array_merge($result, find_files($dir . '/' . $file, $extension));
}
// 如果是文件且文件扩展名匹配,则将其添加到结果数组中
else if (preg_match("/$extension\$/i", $file)) {
$result[] = $dir . '/' . $file;
}
}
}
}
return $result;
}

Transfer Section.php

 隐藏内容:会员可查看
<?php
require("./config.php");
$dbname2 = 'www_azhenxi_com';
$dbname = 'ecms_site';

// 使用 mysqli 执行 SQL 语句
$sql = "SELECT * FROM `{$dbname2}`.`liwuterms`";

$result = mysqli_query($conn, $sql);
$class = mysqli_fetch_all($result,MYSQLI_ASSOC);

turncate($dbname,'phome_enewsclass');
turncate($dbname,'phome_enewsclassadd');

foreach ( $class as $v){
$islast = 1;
$fearthclass = '';
$songclass = '';
$class_sql = "INSERT INTO `{$dbname}`.`phome_enewsclass` (`classid`, `bclassid`, `classname`, `sonclass`, `is_zt`, `lencord`, `link_num`, `newstempid`, `onclick`, `listtempid`, `featherclass`, `islast`, `classpath`, `classtype`, `newspath`, `filename`, `filetype`, `openpl`, `openadd`, `newline`, `hotline`, `goodline`, `classurl`, `groupid`, `myorder`, `filename_qz`, `hotplline`, `modid`, `checked`, `firstline`, `bname`, `islist`, `searchtempid`, `tid`, `tbname`, `maxnum`, `checkpl`, `down_num`, `online_num`, `listorder`, `reorder`, `intro`, `classimg`, `jstempid`, `addinfofen`, `listdt`, `showclass`, `showdt`, `checkqadd`, `qaddlist`, `qaddgroupid`, `qaddshowkey`, `adminqinfo`, `doctime`, `classpagekey`, `dtlisttempid`, `classtempid`, `nreclass`, `nreinfo`, `nrejs`, `nottobq`, `ipath`, `addreinfo`, `haddlist`, `sametitle`, `definfovoteid`, `wburl`, `qeditchecked`, `wapstyleid`, `repreinfo`, `pltempid`, `cgroupid`, `yhid`, `wfid`, `cgtoinfo`, `bdinfoid`, `repagenum`, `keycid`, `allinfos`, `infos`, `addtime`) VALUES ({$v['term_id']}, '0', '{$v['name']}', '{$songclass}', '0', '25', '10', '1', '0', '1', '{$fearthclass}', '{$islast}', 'category/{$v['slug']}', '.html', '', '0', '.html', '0', '1', '10', '10', '10', '', '0', '0', '', '10', '1', '1', '10', '{$v['name']}', '0', '0', '1', 'news', '0', '0', '2', '2', 'id DESC', 'newstime DESC', '', '', '1', '0', '0', '0', '0', '0', '0', '', '0', '0', '0', '', '1', '1', '0', '0', '0', '0', '', '1', '0', '0', '0', '', '0', '0', '0', '0', '', '0', '0', '0', '', '0', '0', '0', '0', '".time()."');";

// print_r($class_sql);die;
if(mysqli_query($conn, $class_sql)){
echo "{$dbname}栏目主表增加成功:{$v['name']}<br>";
}else{
echo "{$dbname}栏目主表增加失败:{$v['name']}<br>";
}
$class_sql = "INSERT INTO `{$dbname}`.`phome_enewsclassadd` (`classid`, `classtext`, `ttids`) VALUES ('{$v['term_id']}', ' ', '');";
// print_r($class_sql);die;
if(mysqli_query($conn, $class_sql)){
echo "{$dbname}栏目副表增加成功:{$v['name']}<br>";
}else{
echo "{$dbname}栏目副表增加失败:{$v['name']}<br>";
}
}

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

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

Author homepage View home page →

Related articles

What should I do if the Redis Object Cache plug-in cannot be linked after wordpress redis changes the password?

What should I do if the Redis Object Cache plug-in cannot be linked after wordpress redis changes the password? Program Notes wordpress

Problem description: My wordpress site server uses pagoda panel, installed php8.0, and installed redis on the extension panel, and installed Redis Object Cache plug-in in wordpress. In fact, in general, you don't need to do anything, just start it directly. However, it is unsafe for radis not to set a password, which is a risky loophole, so I still think it is better to set a password, …
👁 255
How do I disable revisions and automatic draft saving in WordPress?

How do I disable revisions and automatic draft saving in WordPress? Program Notes wordpress

WordPress's automatic article revision tracking feature logs every time you edit an article in the后台; each revision is recorded as a separate entry in the `wp_posts` table. Due to the interplay between article revisions and automatic saving, the article ID often grows larger over time. While this typically does not cause significant issues for your WordPress installation, an excessive number of article versions can place a considerable burden on your storage space and database...
👁 372
Detailed Tutorial on Migrating EmpireCMS Blog Data to WordPress

Detailed Tutorial on Migrating EmpireCMS Blog Data to WordPress Program Notes wordpress

PS1: Second revision – now supports data transfer between categories, posts, and tags. PS2: If the post IDs consistently don't match, you can try clearing the WordPress post category data table and relationship tables. I previously used Typecho for my blog, but later migrated to Empire; however, Empire has too many features – using it for a blog feels like putting a large hammer into a small hole! Additionally, I often record important code snippets in my blog – all of which I've painstakingly written...
👁 546
WordPress issue: pages freezing due to image transcoding

WordPress issue: pages freezing due to image transcoding Program Notes wordpress

Last night, while uploading an image, for some reason, the uploaded image was automatically transcoded. Transcoding type: BASE64 encoding. For an image on a website, simply upload it to your server and then access the link – the image will then be displayed. However, there is another approach: directly transcoding the image; then you can simply access the converted image using its encoded URL. Problem description: When an image is relatively small (e.g., only a few KB in size), transcoding it and then hosting it on a website can help avoid...
👁 152
WordPress database query operations

WordPress database query operations Program Notes wordpress

To connect to a database for a WordPress installation, you need to include the `wp-config.php` file in your PHP script. This file contains the database configuration details for WordPress installation and other constants. Here is a simple example demonstrating how to include the `wp-config.php` file and establish a database connection: // Include the wp-config.php file: require...
👁 377
WordPress MySQL Database Table and Subtable Structure Functionality Guide

WordPress MySQL Database Table and Subtable Structure Functionality Guide Program Notes wordpress

WordPress uses a MySQL database. Its data table structure differs slightly from that of conventional databases; data can be stored either in the form of standard data tables or as data elements – the latter approach is less intuitive when viewed directly. To become a developer, you must understand the basic structure of the WordPress database and be able to use it within your own plugins or themes to write to or read from the database. I. Data Tables – As of WordPress...
👁 374

Recommended reading

Sculpture Machine & Equipment Website Template 0665

Sculpture Machine & Equipment Website Template 0665 Practical Collection Yiyou template

This EyouCMS template is designed for the sculpture machine and mechanical equipment industry, featuring a professional industrial design style that effectively showcases sculpture machine products, mechanical equipment, technical specifications, and industrial applications. It enables machinery manufacturing enterprises to present their products online and attract industrial customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 52
(Adaptive mobile phone version) Immigration and study abroad website pbootcms template Education and training institution website source code download 0372

(Adaptive mobile phone version) Immigration and study abroad website pbootcms template Education and training institution website source code download 0372 Practical Collection pbootcms Template

A mobile-adaptive PbootCMS website template for immigrants, study abroad and education and training. The design style is professional and international, suitable for immigration agencies and study abroad institutions to display services and successful cases. It helps overseas service agencies attract students and families in need online. Template display Installation instructions Website backend: /admin.php Account: admin Password: admin Unzip password: www.4s5.cn Related articles...
👁 47
sqlite uses PDO to execute SQL statements exec(), query()

sqlite uses PDO to execute SQL statements exec(), query() Language Notes mySql

In PHP scripts, executing SQL queries using PDO to interact with a database can be done through three different approaches; the choice of which method to use depends on the specific operation you intend to perform. 1. Using the PDO::exec() method: When executing queries such as INSERT, UPDATE, or DELETE that do not return a result set, use the exec() method on a PDO object to execute the query. Upon successful execution, this method returns the number of affected rows...
👁 323
(PC+WAP) Laboratory Chemical Instrumentation Equipment Website Template 1094

(PC+WAP) Laboratory Chemical Instrumentation Equipment Website Template 1094 Practical Collection pbootcms Template

A PbootCMS website template for laboratory chemical instrumentation and equipment, compatible with both PC and WAP devices. Featuring a professional, tech-oriented design ideal for showcasing laboratory instruments, chemical equipment, and technical expertise. This template helps scientific instrument manufacturers showcase their products online and attract research and testing clients. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 38
Locomotive collector, new dual title generation (the title is super pseudo-original!)

Locomotive collector, new dual title generation (the title is super pseudo-original!) Practical Collection High-speed rail collection

It was written based on the idea of ​​an old man who specializes in garbage dumps! This plug-in is very suitable for that kind of garbage station. After collecting, it will automatically process the titles of the original website and generate a new dual title! It can very well attract crawlers to crawl! Connected to Baidu drop-down, so you don’t have to worry about the plug-in hanging! Generate effect:
👁 315
Responsive office supplies service company website template 0666

Responsive office supplies service company website template 0666 Practical Collection Yiyou template

An eyouCMS responsive website template designed for office supplies and service companies. Its professional and practical design effectively showcases office supply products, corporate services, solutions, and brand identity. This template helps office supply businesses showcase their products online and attract corporate clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for YouyouCMS...
👁 33