Onyx
Onyx

Reputation: 5780

How to turn Curl response into Json so I can use it on the front-end?

I have a function which uses curl_multi to make several GET requests. However, I can't figure out how to turn the response to JSON so I could access it on the front end. Usually I use json_decode(), however, it is not working this time. Maybe it's because I'm trying to decode a whole array of strings instead of a singular string?. Currently the response looks like this on the front-end:

enter image description here

And here's my function:

public function getVisited($username){
    $user = User::where('username', $username)->first();
    $visitedPlaces = $user->visitedPlaces;
    $finalPlaces = [];

    foreach ($visitedPlaces as $visitedPlace) {
        $url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" . $visitedPlace->place_id . "&key=AIzaSyDQ64lYvtaYYYNWxLzkppdN-n0LulMOf4Y";
        array_push($finalPlaces, $url);
    }

    $result = array();
    $curly = array();
    $mh = curl_multi_init();

    foreach ($finalPlaces as $id => $d) {
        $curly[$id] = curl_init();

        $url = $d;
        curl_setopt($curly[$id], CURLOPT_URL,            $url);
        curl_setopt($curly[$id], CURLOPT_HEADER,         0);
        curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curly[$id], CURLOPT_SSL_VERIFYPEER, 0); // Skip SSL Verification

        curl_multi_add_handle($mh, $curly[$id]);
    }

    $running = null;
    do {
        curl_multi_exec($mh, $running);
    } while($running > 0);

    foreach($curly as $id => $c) {
        $result[$id] = curl_multi_getcontent($c);
        curl_multi_remove_handle($mh, $c);
    }

    curl_multi_close($mh);

    return response()->json([
        'sights' => $result
    ], 201);
}

Upvotes: 0

Views: 252

Answers (1)

Uroš Anđelić
Uroš Anđelić

Reputation: 1174

If you are expecting a json string from the curl_multi_getcontent($c) then you should decode it:

$result[$id] = json_decode(curl_multi_getcontent($c));

Then it should be encoded in the response appropriately.

Upvotes: 1

Related Questions