laravel 使用 cURL 获取 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29328184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:15:05  来源:igfitidea点击:

Getting JSON response WITH cURL

phpjsonlaravelcurl

提问by Borjante

It's incredible, I don't know what I'm doing wrong but i've already lost a couple days struggling with this.

太不可思议了,我不知道我做错了什么,但我已经为此苦苦挣扎了几天。

Here is my cURL request from de comand line:

这是来自 de 命令行的 cURL 请求:

curl -i -H "Accept: text/html" http://laravel.project/api/v1/users/4

Which returns

哪个返回

HTTP/1.1 200 OK
Server: nginx/1.6.2
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: no-cache
Date: Sun, 29 Mar 2015 10:33:36 GMT
Set-Cookie: laravel_session=eyJpdiI6ImNPTkZIYVJZSVRKaHBOZTR3SWh0dHc9PSIsInZhbHVlIjoiblpZYVJlN2dBY1ljejNIYUQycXpsNXRWd1I5a3JSRG8wSWdDOWlHVTMrYUcrdDBNVmVuZUNkOGtJb2M4bXFpTFF3cUdoTFZOVXBWXC82Q1luSGd5bjJBPT0iLCJtYWMiOiI0ZTEwOWQxMmVhMzY2NjI1Yzc1MTBmZmRmYjUyOGQwNDlhYzRjOTNiM2FiOWIyN2E1YjA0OTM4YTUxZmNmMzMzIn0%3D; expires=Sun, 29-Mar-2015 12:33:36 GMT; Max-Age=7200; path=/; httponly

{
"data":{
  "id":4,
  "name":"Helena",
  "email":"[email protected]",
  "created_at":"2015-03-26 21:13:16",
  "updated_at":"2015-03-26 21:13:16"
  }
}

So everything looks fine, Content-type is correctly set and response is in JSON. But now watch what happens if I consume the API with curl in PHP.

所以一切看起来都很好,内容类型设置正确,响应是 JSON。但是现在看看如果我在 PHP 中使用 curl 使用 API 会发生什么。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $final_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);

return json_decode($result);

I get this response:

我得到这个回应:

{#165
  +"data": {#167
    +"id": 4
    +"name": "Helena"
    +"email": "[email protected]"
    +"created_at": "2015-03-26 21:13:16"
    +"updated_at": "2015-03-26 21:13:16"
  }
}

And if I return the $result without json_decode i get this:

如果我在没有 json_decode 的情况下返回 $result ,我会得到这个:

"{
  "data":{
    "id":4,
    "name":"Helena",
    "email":"[email protected]",
    "created_at":"2015-03-26 21:13:16",
    "updated_at":"2015-03-26 21:13:16"
  }
}"

The correct response but inside quotes, i've read in phpdocs that curl_opt_returntranfer returns result as string but I can't be the only person on the planet that ust wants to get the json.

正确的响应但在引号内,我在 phpdocs 中读到 curl_opt_returntranfer 将结果作为字符串返回,但我不能是这个星球上唯一想要获取 json 的人。

Please help

请帮忙

EDIT 1

编辑 1

This is my ApiController class

这是我的 ApiController 类

class ApiController extends Controller {

 // Base controller for API Controllers

    protected $statusCode = 200;

    protected function respond($data)
    {
        return Response::json([
           'data' => $data,

        ]);
    }

    protected function respondNotFound($message = 'No data found')
    {
        return Response::json([
            'error' => [
                'message' => $message,
                'status_code' => $this->getStatusCode(),
            ]
        ]);
    }
}

This is my UserController

这是我的用户控制器

class UserController extends ApiController {

  public function show($user)
 {

       if ($user == null)
            return $this->setStatusCode(404)->respondNotFound('User not found');

        return $this->respond($user);
 }

}

回答by TomerM

I think this will solve your problem:

我认为这将解决您的问题:

curl -i -H "Accept: text/html" http://laravel.project/api/v1/users/4 | tr -d '"'

回答by Ganesh

$response = (string)$result;
                    $resp_arr = explode("<!DOCTYPE",$response);
                    $obj = json_decode(trim($japi_arr[0]));
                    if(isset($obj[0]))
                    {
                    $rsp_id = $obj[0]->id;
                    $rsp_name = $obj[0]->name;