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

使用Curl调用GraphQL接口后无法访问data属性,解码结果为int?

问题排查:Curl调用GraphQL接口后无法解析resultList的问题

问题现象

  • 调用GraphQL接口返回的JSON包含resultList数组,但尝试用$result->data访问时,报错:Warning: Attempt to read property "data" on string
  • 对返回结果执行json_decode后,得到的结果类型是int,无法正常解析目标数据

涉及代码片段

function getData($data_String){

    $endpoint = "https://programs.api.cj.com/query";
    $authToken = "pass";
    $qry = '{"query":"{ publisher { contracts(publisherId: \"xxxxxxx\", limit: 1, filters: {advertiserId: \"'.$advertiser_id.'\"}) { totalCount count resultList { startTime endTime status advertiserId programTerms { id name specialTerms { name body } isDefault actionTerms { id actionTracker { id name description type } lockingMethod { type durationInDays } performanceIncentives { threshold { type value } reward { type commissionType value } currency } commissions { rank situation { id name } itemList { id name } promotionalProperties { id name } rate { type value currency } } } } } } } }","variables":null}';

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: Bearer '.$authToken;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);


    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }

    curl_close($ch);

    $data = json_decode($result);


    return $data;

}

问题原因

  1. Curl返回模式错误:CURLOPT_RETURNTRANSFER被设置为0,这会让curl_exec直接把接口响应内容输出到浏览器,而不是将响应字符串赋值给$result变量。此时$result的实际值是int类型(请求成功返回1,失败返回0),这就是json_decode后得到int的根本原因。
  2. 因为$result不是有效的JSON字符串,后续尝试访问$data->data自然会触发类型错误。

修复步骤

  1. 修正Curl返回设置:将curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);改为curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);,让curl将响应内容以字符串形式返回给$result。
  2. 优化JSON解析:可以给json_decode添加第二个参数true,将解析结果转为关联数组,更方便后续取值:
    $data = json_decode($result, true);
    // 之后可以这样获取resultList
    $resultList = $data['data']['publisher']['contracts']['resultList'];
    
  3. 检查变量有效性:确认$advertiser_id变量已正确传入函数,避免因GraphQL查询语法错误导致接口返回非预期内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:01:03