Home > database >  Issues with parsing response json output with php - Visa Developer API
Issues with parsing response json output with php - Visa Developer API

Time:11-18

I am new to the Visa Developer Platform (VDP) APIs and I am running into issues trying to read the output of the response as a json using php. I followed the tutorial here. I am using the Offers Data API.

My goal is to be able to generate a list of deals to be displayed in the frontend. I am trying to do this by reading the json output and parsing the info for the deals.  

This is what the original tutorial had and it works fine:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_PORT, 443);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($curl, CURLOPT_SSLVERSION, 1);
curl_setopt($curl, CURLOPT_SSLCERT, $cert);
curl_setopt($curl, CURLOPT_SSLKEY, $key);

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($curl);  //This output contains the json output as well

$response_info = curl_getinfo($curl); 

To get the information, I am running: $response_data = file_get_contents($response); which does not appear to work. Since the output it not just the json, but with other info, I am not able to run: $arr = json_decode($response,true); to parse the json. This is what the json looks like:

{"ReturnedResults":4,"StartIndex":1,"Offers":[{"indexNumber":1,"offerContentId":105515,"offerId":

and so on. The json starts with {"indexNumber":1 and everything before it needs to be discarded. Please let me know what I can do to fix this, or if there is a better way to accomplish the goal.  Thank you!

CodePudding user response:

Init cURL with CURLOPT_RETURNTRANSFER => true - then you will have your content in $response variable. Without that option, result of curl_exec is always boolean.

CodePudding user response:

Goal

The json starts with {"indexNumber":1 and everything before it needs to be discarded. Please let me know what I can do to fix this, or if there is a better way to accomplish the goal.

Code

The response variable contains a valid json object. Since you only need Offers you can use this code to obtain the Offers:

$response = '{"ReturnedResults":4,"StartIndex":1,"Offers":[{"indexNumber":1,"offerContentId":105515,"offerId":""}]}';

$json = json_decode($response, true);
var_dump($json['Offers']);

Output

array(1) {
  [0]=>
  array(3) {
    ["indexNumber"]=>
    int(1)
    ["offerContentId"]=>
    int(105515)
    ["offerId"]=>
    string(0) ""
  }
}
  • Related