Using curl to access objects returned from GraphQL
P粉615829742
P粉615829742 2024-02-26 18:09:38
0
1
402

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粉615829742
P粉615829742

reply all(1)
P粉955063662

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))
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!