简体   繁体   中英

Problem converting a JSON object to PHP array

Am working on a Laravel application which consumes a backend API still written in Laravel. Am passing an array of data from the frontend to the backend via curl, The data is being passed fine but on the backend/API when I try to decode it to PHP array and get an individual property in the array, I keep getting null. What could I be missing out?

PHP array am passing

  $data = [
            'phone' => '254712345669',
            'name' => 'John Doe',
            'email' => 'doejohn@email.com',
   ];

  $token = session('access_token');

  $letter = GeneralHelper::global_Curl($data , $token , 'api/v1/travel-letter');

Curl function in GeneralHelper to pass data to the backend in Json format

static function global_Curl($data, $token , $url){

        $server = 'http://localhost/digital-apps-apis/public';

        $headers = ["Accept:application/json",
                    "Content-Type:application/json",
                    "Authorization:Bearer ".$token
                    ]; 

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, ($server.'/'.$url));
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
        $response = json_decode(curl_exec($ch));

        dd($response);

        curl_close($ch);

        return $response;
    }

API side where am retrieving the data

 public function getLetter(Request $request){
       return $request->all();
  }

Data on the browser Network tab after returning from API side

{#368
  +"phone": "254712345669"
  +"name": "John Doe"
  +"email": "doejohn@email.com"
}

When I decode the data so that I can get each single property I get null

public function getLetter(Request $request){
         return json_decode($request->all() , true);
  }

if json_decode returns null, it means that the given data is not a valid json string. the fact that in the network response the string starts with a #368 suggests me that is an object dump rather than a string. Try to double check that.

Also, probably you know that and it's a leftover form the debug but you have a dd() inside your global_Curl function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM