【问题标题】:Get Json file from laravel controller从 laravel 控制器获取 Json 文件
【发布时间】:2017-12-04 16:01:03
【问题描述】:

我需要打印由托管在不同服务器中的 Laravel 控制器方法传递的 json 文件。发送这样的代码,

  function curlrequest($url, $data){  

        $handle = curl_init($url);
        curl_setopt($handle, CURLOPT_POST, true);
        curl_setopt($handle, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); 

        $output = curl_exec($handle);


        if($output === FALSE) {
                    die(curl_error($handle));
                  }else{

                    return $output;
                  }  

         curl_close($handle);  

        }  

在接收器 php 文件(本机 php)中,我有以下代码,

echo '<pre>'.print_r(json_decode(file_get_contents("http://xxx.xxx.xx.xx/myproject/public/send")),1).'</pre>';

在我的 web.php 文件中,我有

Route::get('/send', 'Test\SendController@main'); 

我还没有运行此代码。但我看到我们无法使用 file_get_content 方法访问路由。谁能告诉我在这种情况下传递 json 的正确方法是什么?

【问题讨论】:

    标签: php json laravel-5.4


    【解决方案1】:

    您的问题似乎有点不清楚,但据我所知,您希望从http://xxx.xxx.xx.xx/myproject/public/send 获取 JSON 输出并将其打印到您的 PHP 代码中。

    一个简单的方法是使用GuzzleHttp

    例子:

    $client = new \GuzzleHttp\Client();
    $result = $client->request('GET', 'http://xxx.xxx.xx.xx/myproject/public/send');
    echo $result->getBody();
    

    【讨论】: