我使用 GraphQL/curl 返回了数据,如下所示:
{ "data" : { "publisher" : { "contracts" : { "totalCount" : 11, "count" : 1, "resultList" : [
我想要获取 resultList 数组,并在尝试执行 $result->data 移动到第一个对象时不断收到错误“警告:尝试读取字符串上的属性“数据””。我做错了什么?
curl 请求中的变量是 $result。
更新:我已经尝试解码,返回的数据是 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; }
P粉9550636622024-02-27 14:54:39
首先,请务必检查结果是否是有效的 json。
然后使用json_decode获取对象
$result = json_decode($result); if (is_object($result)) { if (!empty($result->data->publisher->contracts->resultList)) { $resultList = $result->data->publisher->contracts->resultList; } } else { // Log or something error_log("json decode return: " . print_r($result, true)) }