【问题标题】:Get data from external api using guzzle laravel4使用 guzzle laravel4 从外部 api 获取数据
【发布时间】:2015-12-04 04:41:19
【问题描述】:

我正在尝试在 laravel 4 中使用 Guzzle 4.0 从外部 API 获取数据。

我试过了

$client = new \GuzzleHttp\Client();
$response = $client->get('https://openexchangerates.org/api/latest.json?app_id=************');
echo "<pre>";
dd($response->getBody());

它给了我 Guzzle 对象而不是 JSON 响应,我直接在浏览器中点击了那个提供正确 json 数据的 url。

我得到的回复:

object(GuzzleHttp\Stream\Stream)#151 (6) {
["stream":"GuzzleHttp\Stream\Stream":private]=>
resource(6) of type (stream)
["size":"GuzzleHttp\Stream\Stream":private]=>
NULL
["seekable":"GuzzleHttp\Stream\Stream":private]=>
bool(true)
["readable":"GuzzleHttp\Stream\Stream":private]=>
bool(true)
["writable":"GuzzleHttp\Stream\Stream":private]=>
bool(true)
["uri":"GuzzleHttp\Stream\Stream":private]=>
string(10) "php://temp"
}

谁能告诉我怎样才能得到正确的json数据。

提前感谢您的支持。

【问题讨论】:

    标签: php laravel guzzle


    【解决方案1】:

    尝试将正文转换为字符串:

    dd((string) $response->getBody());
    

    getBody() 方法实际上返回一个对象,这是设计使然。如果您尝试将其用作字符串,它会自动转换为字符串,例如echo

    不过,在您的 dd() 调用中,您需要显式转换为字符串,否则您将获得对象输出。

    这是来自文档:

    可以使用 getBody 方法检索响应的正文。主体可以用作字符串,转换为字符串,或用作类似对象的流。

    $body = $response->getBody();
    // Implicitly cast the body to a string and echo it
    echo $body;
    // Explicitly cast the body to a string
    $stringBody = (string) $body;
    

    更多详情请看这里:

    http://docs.guzzlephp.org/en/latest/quickstart.html#using-responses

    【讨论】:

    • 感谢您的回答,通过使用这个我可以获得字符串,但我的问题没有解决,因为我还需要在数据库中存储值:(
    • 如果可以得到字符串,可以使用json_decode将其解析为json。或者,正如 Jason 在下面提到的那样,只需调用 $response-&gt;json()。获得解析后的 JSON 数据后,您可以提取各个值并存储在数据库中。
    【解决方案2】:

    如果您的响应确实是 JSON,您可以在响应对象上调用 json() 方法返回一个 JSON 数组。

    print_r($response->json());
    

    这在一个调用中完成了转换和解析,我觉得这更干净一些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-06
      • 2021-06-23
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      相关资源
      最近更新 更多