Home  >  Q&A  >  body text

Using curl to access objects returned from GraphQL

I returned the data using GraphQL/curl like this:

{
  "data" : {
    "publisher" : {
      "contracts" : {
        "totalCount" : 11,
        "count" : 1,
        "resultList" : [

I want to get a resultList array and keep getting the error "Warning: Attempting to read property 'data' on string" when trying to do $result->data to move to the first object. What did i do wrong?

The variable in the curl request is $result.

Update: I have tried decoding, is the data returned an INT type? what to do?

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粉615829742P粉615829742210 days ago347

reply all(1)I'll reply

  • P粉955063662

    P粉9550636622024-02-27 14:54:39

    First, be sure to check if the result is valid json.

    Then use json_decode to get the object

    $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))
    }

    reply
    0
  • Cancelreply