【问题标题】:Using Guzzle to get data - Strange Error使用 Guzzle 获取数据 - 奇怪的错误
【发布时间】:2016-08-29 21:43:45
【问题描述】:

这是我的代码

public function getAllCountries() {
    $countries = array();
    $response = $this->client->get($this->geoCountryAPIURL, [
        'query' => ['username' => $this->username]
    ]);
    $body = json_decode($response->getBody()->getContents());
    if ($response->getStatusCode() == 200) {
        if (array_key_exists('geonames', $body)) {
            $dataRespone = $body->geonames;
            // error or status response
            foreach ($dataRespone as $country)
            {
                $countries[] = array(
                    'geonameId' => $country->geonameId,
                    'countryName' => $country->countryName
                );
            }
        }
    }
    return $countries;
}

在我的 PHP 错误日志中,我收到此错误:

PHP 致命错误:无法在第 35 行使用 stdClass 类型的对象作为数组

第 35 行是

if ($response->getStatusCode() == 200) {

【问题讨论】:

  • var_dump($respons); 会帮助你。
  • 我正在了解国家/地区。我从 stdClass 错误中得到这个数组。任何方式我都可以通过 guzzle 做到这一点

标签: php laravel guzzle


【解决方案1】:

json_decode() 返回一个对象,除非您将true 作为第二个参数传递。

即使它说错误在第 35 行,它也可能在下一行。错误消息并不总是 100% 正确,但通常会为您提供一个良好的起点。

所以,它实际抱怨的可能是这样的:

if (array_key_exists('geonames', $body)) {

..因为$body 是一个对象。

将该行更改为:

if (property_exists($body, 'geonames)) {

...它应该可以工作。

您确定foreach ($dataRespone as $country) 是正确的吗?我不知道响应是什么样的,但是:foreach ($dataRespone->geonames as $country) 似乎更有可能。据我所知,您不能循环 StdClass-object。

【讨论】:

  • pastebin.com/Gk8130fU 完整代码。 imgur.com/a/Q6v8d 是这段代码的响应
  • 您现在遇到什么错误?相同还是不同?
  • PHP 致命错误:无法在第 43 行的 LocationHelper.php 中使用 stdClass 类型的对象作为数组
  • 您尝试了我回答的最后一部分吗?更改 foreach?
  • 第 43 行 = $countries[] = array( 'geonameId' => $country->geonameId, 'countryName' => $country->countryName );
猜你喜欢
  • 2020-04-25
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
相关资源
最近更新 更多