【问题标题】:Problem converting a JSON object to PHP array将 JSON 对象转换为 PHP 数组时出现问题
【发布时间】:2019-08-01 09:23:55
【问题描述】:

我正在开发一个 Laravel 应用程序,该应用程序使用仍然用 Laravel 编写的后端 API。我通过 curl 将一组数据从前端传递到后端,数据被很好地传递,但在后端/API 上,当我尝试将其解码为 PHP 数组并获取数组中的单个属性时,我一直为空。我会错过什么?

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');

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 端

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

从 API 端返回后浏览器网络选项卡上的数据

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

当我解码数据以获取每个属性时,我得到 null

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

【问题讨论】:

  • 我不明白你在哪里得到空值。无论如何,您可以尝试打印您传递给 API 服务器的参数并查看它们是否存在。

标签: php json api decode


【解决方案1】:

如果json_decode返回null,则表示给定数据不是有效的json字符串。在网络响应中字符串以#368 开头的事实表明这是一个对象转储而不是字符串。尝试仔细检查。

另外,您可能知道,它是调试的剩余部分,但您的 global_Curl 函数中有一个 dd()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-11
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2020-12-19
    • 1970-01-01
    • 2017-09-13
    相关资源
    最近更新 更多