alexistdev
alexistdev

Reputation: 61

Cant Extract data from PHP curl response

I learning to use API from: https://rapidapi.com/lambda/api/face-recognition-and-face-detection/endpoints

I want to save or echo albumkey to variable and store in database. I have tried $response->albumkey and didn't work.

here my response below:

    {
      album: "amanda11",
      msg: "Please put this in a safe place and remember it, you'll need it!",
      albumkey: "c00bc5d3b1bf64a1ba68f690d4dabee494a2c6fbf48cf8f09c6d41fbece45b7b"
    }

And here my code:

$curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => "https://lambda-face-recognition.p.rapidapi.com/album",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "album=amanda11",
            CURLOPT_HTTPHEADER => [
                "content-type: application/x-www-form-urlencoded",
                "x-rapidapi-host: lambda-face-recognition.p.rapidapi.com",
                "x-rapidapi-key: 932571abf0msh45cf0f3cef74aacp19e151jsn33e9949a1974"
            ],
        ]);
        $response = curl_exec($curl);
        $err = curl_error($curl);
        if ($err) {
            echo $err;
        } else {
            echo $response;
        }

Upvotes: 0

Views: 96

Answers (1)

John Conde
John Conde

Reputation: 219804

You need to parse the JSON before you can access its values. In PHP you do that with json_decode():

$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
    echo $err;
} else {
    $json = json_decode($response);
    echo $json->albumkey ;
}

Here's a basic example:

$response = '{
  "album": "amanda11",
  "msg": "Please put this in a safe place and remember it, you\'ll need it!",
  "albumkey": "c00bc5d3b1bf64a1ba68f690d4dabee494a2c6fbf48cf8f09c6d41fbece45b7b"
}';
$json = json_decode($response);
echo $json->albumkey;

Demo

Upvotes: 2

Related Questions