Search code examples
phpjsonvisa-api

Issues with parsing response json output with php - Visa Developer API


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!


Solution

  • 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) ""
      }
    }