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

Drupal自定义模块通过cURL获取JSON后替换键值的问题求助

问题原因

你现在拿不到索引、无法完成替换的核心原因是代码存在几个基础错误,加上没有实现对应的键值转换逻辑:

  • cURL错误检测的变量名不匹配:初始化cURL句柄用的变量是$curl,但错误判断时写的是未定义的$ch,请求出错时根本不会触发提示
  • JSON解码格式不对:json_decode()默认返回标准对象类型,不是你注释里写的数组,无法直接按数组索引方式取值改键
  • 方法没有返回值:getResult()方法里处理完数据后,返回语句被注释,外层接口拿不到处理后的结果
  • 没有写键名替换的逻辑:缺少遍历数据、替换指定键名的代码段
修复后可直接运行的代码
<?php
 
namespace Drupal\custom_rest_services\Controller;

use Symfony\Component\HttpFoundation\JsonResponse;

class custom_rest_servicesController {
  public function converter_json_formio() { 
    return new JsonResponse([
      'data' => $this->getResult(),
      'method' => 'GET',
    ]);
  }
  
  private function getResult(){
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => 'http://localhost/install-dir/web/webform_rest/feedback_13/fields',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => array(
        'Authorization: Basic YWRtaW46QWRtaW5AMTIz'
      ),
    ));
    
    $result = curl_exec($curl);

    // 错误检测用正确的cURL句柄变量
    if (curl_errno($curl)) { 
      // 生产环境建议用Drupal自带日志记录,不要直接输出错误
      \Drupal::logger('custom_rest_services')->error(curl_error($curl));
      return [];
    }
    curl_close($curl);

    // 传入第二个参数true,将JSON转成关联数组,方便按索引操作
    $decoded = json_decode($result, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
      \Drupal::logger('custom_rest_services')->error('JSON解析失败:' . json_last_error_msg());
      return [];
    }

    // 键名替换规则,键是原键名,值是替换后的目标键名
    $keyReplaceMap = [
      'title' => 'label',
      // 后续需要替换其他键直接在这里加即可,比如 '#title' => 'label' 这类Webform特有的键
    ];

    // 递归处理所有层级的键名替换,适配Webform返回的多层嵌套结构
    $replaceKey = function($data) use (&$replaceKey, $keyReplaceMap) {
      if (!is_array($data)) {
        return $data;
      }
      $newData = [];
      foreach ($data as $key => $value) {
        // 匹配到需要替换的键就用新键名,否则保留原键
        $newKey = array_key_exists($key, $keyReplaceMap) ? $keyReplaceMap[$key] : $key;
        $newData[$newKey] = is_array($value) ? $replaceKey($value) : $value;
      }
      return $newData;
    };

    return $replaceKey($decoded);
  }
}
使用说明
  • 键名替换规则统一维护在$keyReplaceMap数组里,需要新增替换规则直接加键值对即可
  • 递归逻辑会自动处理Webform返回的多层嵌套字段结构,不需要手动逐层写遍历
  • 把原来直接echo/print_r的调试代码换成了Drupal自带的日志记录,避免接口返回格式错乱
  • 增加了JSON解析错误的判断,避免接口返回异常数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 21:54:21