【问题标题】:How to send JSON and retrieve it using cURL?如何发送 JSON 并使用 cURL 检索它?
【发布时间】:2015-03-30 04:52:21
【问题描述】:

此链接 = http://localhost/api_v2/url?key=***

将返回此 JSON 列表:

我已经测试过:

  • 通过浏览器导航到http://localhost/api_v2/url?key=***
  • 并通过命令行$ curl http://localhost/api_v2/url?key=*** 发出 curl 请求
  • 无论哪种方式都会返回 JSON,并给我相同的结果。
  • 嗯,我可以看出我的$array 正在其中存储一些东西。
  • 即使我做了dd($array) - 我仍然得到相同的结果。

这就是我所拥有的


这是我建立 JSON 的方法

public function index_2(){

    $file_name = 'inventory.csv';
    $file_path = 'C:\\QuickBooks\\'.$file_name;
    $csv= file_get_contents($file_path);
    $utf8_csv = utf8_encode($csv);
    $array = array_map("str_getcsv", explode("\n", $utf8_csv));

    return Response::json($array);

}

这是我提出 cURL 请求并尝试检索该 JSON 的方式

<?php 

    $ch = curl_init("http://localhost/api_v2/url?key=***");
    curl_setopt($ch, CURLOPT_USERPWD, "admin:*****");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $body = curl_exec($ch);
    curl_close($ch);

    $json_decode = json_decode($array, TRUE);

我一直抱怨 $array 变量没有定义,但实际上我确实定义并发送它像这样return Response::json($array);

我不确定我在这里做错了什么。

【问题讨论】:

  • json_decode($body) 怎么样?
  • 成功了!!你说得对。谢谢@lukasgeiter

标签: php json laravel curl


【解决方案1】:

找出不同之处:

$body = curl_exec($ch);
^^^^^

$json_decode = json_decode($array, TRUE);
                           ^^^^^^

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 2014-03-07
    • 2018-12-15
    • 2022-11-03
    • 1970-01-01
    • 2022-08-07
    • 2011-06-24
    • 2023-03-10
    • 2011-07-05
    相关资源
    最近更新 更多