Context:
I am trying to notify myself with an email whenever there is a reputation change on my account every 30 mins(which will come via a cron job). So I am hitting a StackExchange API to get this.
Problem:
When I hit the API, I get a pretty weird character stream like below:
API Endpoint:
https://api.stackexchange.com/2.3/users/4964822/reputation?page=1&pagesize=10&fromdate=1672527600&todate=1672527600&site=stackoverflow
Snippet:
<?php
namespace StackbotNotifier\Controllers;
class APIController{
public const API_DOMAIN = 'https://api.stackexchange.com/2.3/';
public const API_ENDPOINTS = [
'REPUTATION.CHANGE' => 'users/4964822/reputation',
'INBOX.UNREAD' => 'inbox/unread'
];
public static function makeAPICall($endPointURI, $params = [], $method = 'GET'){
try{
$method = strtoupper($method);
$ch = curl_init();
$absoluteEndpoint = self::API_DOMAIN . self::API_ENDPOINTS[ $endPointURI];
if($method == 'GET'){
$absoluteEndpoint .= '?' . http_build_query($params);
}
curl_setopt($ch, CURLOPT_URL, $absoluteEndpoint);
if($method == 'POST'){
curl_setopt($ch, CURLOPT_POST, true);
}else{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}
$headers = ['Accept:application/json'];
if($method != 'GET'){
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
$headers[] = 'Content-Type:application/json';
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, ini_get('openssl.cafile'));
$response = curl_exec($ch);
$curl_info = curl_getinfo($ch);
if(preg_match('/^2\d\d$/',$curl_info['http_code']) !== 1){
throw new \Exception("Error occurred with http status ".$curl_info['http_code']." !! Response is ". $response);
}
curl_close($ch);
return $response;
}catch(\Exception $e){
die($e->getMessage());
}
}
}
Driver Code:
<?php
use StackbotNotifier\Controllers\APIController;
echo APIController::makeAPICall(APIController::API_ENDPOINTS['REPUTATION.CHANGE'], [
'page' => 1,
'pagesize' => 10,
'fromdate' => '2022-12-30',
'todate' => '2023-01-01',
'site' => 'stackoverflow'
]);
Can anybody help me out with the same? My controller has a straightforward cURL request and yet it fails to give me a proper JSON.