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

如何从JSON输出获取PHP数组并将API数据存入MySQL数据库

没问题,我来一步步帮你搞定从API拉取JSON数据、转成PHP数组并存入MySQL的完整流程,结合你给出的代码片段来完善:

完整实现流程

1. 拉取API数据并解析为PHP数组

首先补全API请求代码,同时加入错误处理,避免请求或解析失败导致的崩溃:

$url = "https://api-url"; // 替换成你的实际API地址
$jsonString = file_get_contents($url);

// 检查API请求是否成功
if ($jsonString === false) {
    die("无法获取API数据,请检查URL或网络连接");
}

// 将JSON字符串转为PHP关联数组(加true参数避免生成对象)
$data = json_decode($jsonString, true);

// 检查JSON解析是否正常
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON解析失败:" . json_last_error_msg());
}

如果你的PHP环境关闭了allow_url_fopen,可以用cURL替代file_get_contents,兼容性更好:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 生产环境建议开启SSL验证
$jsonString = curl_exec($ch);
curl_close($ch);

2. 提取feeds中的目标数据

用foreach循环遍历feeds数组,同时先做存在性检查,避免数组不存在时报错:

// 先确认feeds数组存在且不为空
if (isset($data['feeds']) && is_array($data['feeds']) && !empty($data['feeds'])) {
    foreach ($data['feeds'] as $feed) {
        $recordTime = $feed['created_at'];
        $currentValue = $feed['field1']; // 对应JSON里的电流值
        
        // 测试阶段可以先打印数据,确认提取正确
        // echo "记录时间:{$recordTime},电流值:{$currentValue}<br>";
    }
} else {
    die("feeds数据不存在或为空");
}

3. 连接MySQL并插入数据

第一步:创建数据库表

先在MySQL中创建存储数据的表(可以通过phpMyAdmin或命令行执行):

CREATE TABLE IF NOT EXISTS sensor_current_data (
    id INT AUTO_INCREMENT PRIMARY KEY,
    channel_id INT NOT NULL,
    current_value DECIMAL(10,5) NOT NULL,
    record_time DATETIME NOT NULL,
    INDEX idx_channel (channel_id),
    INDEX idx_record_time (record_time)
);

第二步:PHP代码实现插入

用PDO连接数据库(比mysqli更安全,自带防SQL注入机制),把提取到的数据存入表中:

// 数据库配置信息,替换成你的实际参数
$dbHost = 'localhost';
$dbName = 'your_database_name';
$dbUser = 'your_db_username';
$dbPass = 'your_db_password';

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

    // 获取频道ID,一起存入数据库方便后续关联
    $channelId = $data['channel']['id'];

    // 遍历feeds插入数据
    if (isset($data['feeds']) && is_array($data['feeds']) && !empty($data['feeds'])) {
        foreach ($data['feeds'] as $feed) {
            $recordTime = $feed['created_at'];
            // 把ISO时间格式转成MySQL兼容的datetime格式(兼容低版本MySQL)
            $mysqlTime = date('Y-m-d H:i:s', strtotime($recordTime));
            $currentValue = $feed['field1'];

            // 预处理SQL语句,防止SQL注入
            $stmt = $pdo->prepare("INSERT INTO sensor_current_data (channel_id, current_value, record_time) VALUES (:channel_id, :current_value, :record_time)");
            $stmt->bindParam(':channel_id', $channelId, PDO::PARAM_INT);
            $stmt->bindParam(':current_value', $currentValue, PDO::PARAM_STR);
            $stmt->bindParam(':record_time', $mysqlTime, PDO::PARAM_STR);

            // 执行插入
            $stmt->execute();
            echo "数据插入成功:{$mysqlTime} - 电流值 {$currentValue}<br>";
        }
    } else {
        echo "没有可插入的有效数据";
    }
} catch(PDOException $e) {
    die("数据库操作失败:" . $e->getMessage());
}

// 关闭连接(PDO会自动回收,这一步可选)
$pdo = null;

4. 生产环境注意事项

  • 不要用die()直接终止程序,建议用日志记录错误,给用户友好的提示
  • 如果API可能返回重复数据,可以根据last_entry_id或record_time+current_value做去重逻辑
  • 确保数据库用户只有必要的权限(比如仅INSERT权限),提升安全性
  • 可以加入定时任务(比如Linux的Cron),定期拉取API数据存入数据库

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:40:24