【问题标题】:Accessing specific properties from Guzzle response?从 Guzzle 响应中访问特定属性?
【发布时间】:2016-12-05 23:25:46
【问题描述】:

我正在使用 Guzzle 获取 HTTP 响应。如果我这样做:

$response = $res->getBody();

我得到一个带有“电子邮件”作为属性之一的对象。但如果我这样做:

$email = $res->getBody()->email;

$email = $response->email

我收到“电子邮件没有价值”错误。我错过了什么??如何访问响应对象中的特定属性?

【问题讨论】:

    标签: php guzzle


    【解决方案1】:

    getBody 方法返回一个StreamInterface 的实例。你首先需要retrieve the contents of the response:

    $response = (string) $res->getBody();
    

    只有这样你才能解码 json 有效载荷:

    $json = json_decode($response); 
    $email = $json->email;
    

    【讨论】:

    • 这感觉又丑又丑,真的没有更好的解决方法吗?
    • 您可以在一行中完成所有操作。喜欢:json_decode($res->getBody())->email
    猜你喜欢
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多