You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP格式化系统信息文本并存储到MySQL数据库?

实现步骤

1. 文本预处理与解析

先清理原始文本中的冗余内容(如开头的b'、空行、多余缩进),再逐行识别字段与对应值,重点处理跨多行的字段内容(如操作系统版本、处理器信息)。

代码示例:文本解析

<?php
// 已翻译字段名的原始系统信息文本
$rawText = <<<TEXT
主机名:                            DESKTOP-5AB1DJ9
操作系统名称:              Microsoft Windows 10 Pro
操作系统版本:     
    10.0.19044 N/D Compilación 19044
操作系统制造商:          Microsoft Corporation
操作系统配置:       独立工作站
操作系统编译类型: Multiprocessor Free
所有者:                              Usuario
注册组织:   
            
产品ID:                          00330-80000-00000-AA120
原始安装日期:             27/09/2020, 8:19:08
系统启动时间:            11/07/2022, 15:54:10
系统制造商:                    ASUSTeK COMPUTER INC.
系统型号:                         ZenBook UX533FD_UX533FD
系统类型:                           x64-based PC
处理器:                            1个处理器已安装。

    [01]: Intel64 Family 6 Model 142 Stepping 12 GenuineIntel ~1792 Mhz
BIOS版本:                          American Megatrends Inc. UX533FD.306, 16/10/2019
Windows目录:                     C:\Windows
系统目录:                     C:\Windows\system32
启动设备:                   \Device\HarddiskVolume1
系统区域设置:        es;西班牙语(国际)
输入语言:                         es;西班牙语(传统)
时区:                              (UTC+01:00) 布鲁塞尔、哥本哈根、马德里、巴黎
物理内存总量:          16.198 MB
可用物理内存:                 4.145 MB
虚拟内存: 最大大小:            22.563 MB
虚拟内存: 可用:               3.330 MB
TEXT;

// 清理文本:移除冗余标识、空行,拆分每行
$cleanedText = preg_replace('/^b\'/', '', $rawText);
$cleanedText = preg_replace('/^\s*$/m', '', $cleanedText);
$lines = explode("\n", $cleanedText);

$systemInfo = [];
$currentKey = '';

foreach ($lines as $line) {
    $line = trim($line);
    if (empty($line)) continue;

    // 识别字段行(含冒号)
    if (strpos($line, ':') !== false) {
        list($key, $value) = explode(':', $line, 2);
        $key = trim($key);
        $value = trim($value);
        
        if (!empty($value)) {
            $systemInfo[$key] = $value;
            $currentKey = $key;
        } else {
            $currentKey = $key;
            $systemInfo[$currentKey] = '';
        }
    } else {
        // 多行值追加到当前字段
        if (!empty($currentKey)) {
            $systemInfo[$currentKey] .= ' ' . $line;
        }
    }
}

// 清理处理器字段的多余空格
if (isset($systemInfo['处理器'])) {
    $systemInfo['处理器'] = preg_replace('/\s+/', ' ', $systemInfo['处理器']);
}

// 输出解析结果(可根据需求调整)
print_r($systemInfo);
?>

2. MySQL数据库存储

第一步:创建存储表

根据解析后的字段创建对应表结构:

CREATE TABLE system_info (
    id INT AUTO_INCREMENT PRIMARY KEY,
    host_name VARCHAR(255) NOT NULL,
    os_name VARCHAR(255) NOT NULL,
    os_version TEXT,
    os_manufacturer VARCHAR(255),
    os_config VARCHAR(255),
    os_build_type VARCHAR(255),
    owner VARCHAR(255),
    registered_org VARCHAR(255),
    product_id VARCHAR(255),
    install_date DATETIME,
    boot_time DATETIME,
    system_manufacturer VARCHAR(255),
    system_model VARCHAR(255),
    system_type VARCHAR(255),
    processor TEXT,
    bios_version VARCHAR(255),
    windows_dir VARCHAR(255),
    system_dir VARCHAR(255),
    boot_device VARCHAR(255),
    system_locale VARCHAR(255),
    input_language VARCHAR(255),
    time_zone VARCHAR(255),
    total_physical_memory VARCHAR(50),
    available_physical_memory VARCHAR(50),
    max_virtual_memory VARCHAR(50),
    available_virtual_memory VARCHAR(50),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

第二步:PHP插入数据

使用PDO连接数据库,通过预处理语句安全插入数据:

<?php
// 数据库连接参数
$host = 'localhost';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';

try {
    // 初始化PDO连接
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 准备插入语句
    $stmt = $pdo->prepare("INSERT INTO system_info (
        host_name, os_name, os_version, os_manufacturer, os_config, os_build_type,
        owner, registered_org, product_id, install_date, boot_time, system_manufacturer,
        system_model, system_type, processor, bios_version, windows_dir, system_dir,
        boot_device, system_locale, input_language, time_zone, total_physical_memory,
        available_physical_memory, max_virtual_memory, available_virtual_memory
    ) VALUES (
        :host_name, :os_name, :os_version, :os_manufacturer, :os_config, :os_build_type,
        :owner, :registered_org, :product_id, :install_date, :boot_time, :system_manufacturer,
        :system_model, :system_type, :processor, :bios_version, :windows_dir, :system_dir,
        :boot_device, :system_locale, :input_language, :time_zone, :total_physical_memory,
        :available_physical_memory, :max_virtual_memory, :available_virtual_memory
    )");

    // 格式化日期为MySQL支持的格式
    $installDate = DateTime::createFromFormat('d/m/Y, H:i:s', $systemInfo['原始安装日期']);
    $bootTime = DateTime::createFromFormat('d/m/Y, H:i:s', $systemInfo['系统启动时间']);

    // 绑定参数
    $stmt->bindParam(':host_name', $systemInfo['主机名']);
    $stmt->bindParam(':os_name', $systemInfo['操作系统名称']);
    $stmt->bindParam(':os_version', $systemInfo['操作系统版本']);
    $stmt->bindParam(':os_manufacturer', $systemInfo['操作系统制造商']);
    $stmt->bindParam(':os_config', $systemInfo['操作系统配置']);
    $stmt->bindParam(':os_build_type', $systemInfo['操作系统编译类型']);
    $stmt->bindParam(':owner', $systemInfo['所有者']);
    $stmt->bindParam(':registered_org', $systemInfo['注册组织']);
    $stmt->bindParam(':product_id', $systemInfo['产品ID']);
    $stmt->bindParam(':install_date', $installDate ? $installDate->format('Y-m-d H:i:s') : null);
    $stmt->bindParam(':boot_time', $bootTime ? $bootTime->format('Y-m-d H:i:s') : null);
    $stmt->bindParam(':system_manufacturer', $systemInfo['系统制造商']);
    $stmt->bindParam(':system_model', $systemInfo['系统型号']);
    $stmt->bindParam(':system_type', $systemInfo['系统类型']);
    $stmt->bindParam(':processor', $systemInfo['处理器']);
    $stmt->bindParam(':bios_version', $systemInfo['BIOS版本']);
    $stmt->bindParam(':windows_dir', $systemInfo['Windows目录']);
    $stmt->bindParam(':system_dir', $systemInfo['系统目录']);
    $stmt->bindParam(':boot_device', $systemInfo['启动设备']);
    $stmt->bindParam(':system_locale', $systemInfo['系统区域设置']);
    $stmt->bindParam(':input_language', $systemInfo['输入语言']);
    $stmt->bindParam(':time_zone', $systemInfo['时区']);
    $stmt->bindParam(':total_physical_memory', $systemInfo['物理内存总量']);
    $stmt->bindParam(':available_physical_memory', $systemInfo['可用物理内存']);
    $stmt->bindParam(':max_virtual_memory', $systemInfo['虚拟内存: 最大大小']);
    $stmt->bindParam(':available_virtual_memory', $systemInfo['虚拟内存: 可用']);

    // 执行插入
    $stmt->execute();
    echo "系统信息已成功存储到数据库";
} catch(PDOException $e) {
    die("数据库操作失败: " . $e->getMessage());
}
?>

关键注意事项

  • 多行值处理:通过跟踪当前字段,将后续行内容追加到对应字段,解决跨多行信息的解析问题。
  • 日期转换:将原始文本中的dd/mm/yyyy格式日期转换为MySQL兼容的yyyy-mm-dd格式。
  • 安全防护:使用PDO预处理语句绑定参数,避免SQL注入风险。
  • 文本清理:先移除冗余标识和空行,确保解析逻辑不受干扰。

内容的提问来源于stack exchange,提问作者K10YW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:57:41