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

PHP关闭allow_url_fopen时如何用CURL调用Canvas GraphiQL接口

代码存在的问题

  • 端点地址错误:你使用的/graphiql是Canvas提供的GraphQL可视化调试页面地址,真实的API请求端点应为/graphql
  • POST请求体格式不符合要求:GraphQL POST请求需要传递JSON格式的结构体,你直接传入了查询字符串,需要将查询语句封装到query字段后做JSON编码
  • 输出逻辑错误:json_decode返回的是数组类型,直接使用echo输出会触发PHP警告,需使用print_r/var_dump打印结构,也可以按需提取字段输出

修正后的代码

<?php
// 修正为真实GraphQL API端点
$endpoint = "https://xxx.instructure.com/graphql";
$authToken = "XXXXXXXXXXXXXXXXXXXXX";
$qry = "query {allCourses {name assignmentsConnection { nodes {name dueAt } } }}";

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

// 封装符合要求的POST请求体
$postData = json_encode([
    'query' => $qry
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 调试阶段如果遇证书验证问题可临时开启下面两行配置,线上环境建议保持默认开启SSL验证
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Curl错误:' . curl_error($ch);
}
curl_close($ch);

$decoded = json_decode($result, TRUE);
// 打印返回结果
print_r($decoded);
// 可直接判断接口返回的错误字段做异常处理
if (isset($decoded['errors'])) {
    echo "接口返回错误:";
    print_r($decoded['errors']);
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:15:03