简体   繁体   English

将JSON对象转换为PHP数组时出现问题

[英]Problem converting a JSON object to PHP array

Am working on a Laravel application which consumes a backend API still written in Laravel. 我正在使用Laravel应用程序,该应用程序使用仍使用Laravel编写的后端API。 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. 我正在通过curl从前端向后端传递数据数组,数据传递得很好,但是当我尝试将其解码为PHP数组并在数组中获得单个属性时,在后端/ API上,我一直为null。 What could I be missing out? 我可能会错过什么?

PHP array am passing PHP数组正在传递

  $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 GeneralHelper中的Curl函数以Json格式将数据传递到后端

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 API端正在检索数据

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

Data on the browser Network tab after returning from API side 从API端返回后,浏览器“网络”标签上的数据

{#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 当我解码数据以便获得每个单个属性时,我将得到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. 如果json_decode返回null,则意味着给定的数据不是有效的json字符串。 the fact that in the network response the string starts with a #368 suggests me that is an object dump rather than a string. 在网络响应中,字符串以#368开头的事实表明,这是对象转储而不是字符串。 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 另外,可能您知道这是调试的剩余内容,但是在global_Curl函数中有一个dd()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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