【问题标题】:cURL: Uncaught Error: Object of class stdClass could not be converted to stringcURL:未捕获的错误:stdClass 类的对象无法转换为字符串
【发布时间】:2021-07-16 16:42:00
【问题描述】:

不知道为什么会出现以下错误:

Uncaught Error: Object of class stdClass could not be converted to string

我正在学习这里的教程:

https://www.youtube.com/watch?v=ZIsdbVOQJNc&t=20s

大约 6:16 分钟是我所在的位置。

这是我的代码:

<?php
  $url = "http://localhost/restapi/";

  $data_array = array(
    'username' => 'jbeasley',
    'fullname' => 'John Beasley',
    'email' => 'jbeasley@email.com'
  );

  $data = http_build_query($data_array);

  $ch = curl_init($url);

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  $resp = curl_exec($ch);

  if($e = curl_error($ch)) {
    echo $e;
  } else {
    $decoded = json_decode($resp);
    foreach($decoded as $key => $val) {
        echo $key . ': ' . $val . '<br>';  // <-- error is pointing here
    }
  }

  curl_close($ch);
?>

错误指向foreach循环中的$val变量。

实际的 API 如下所示:

<?php
  require_once __DIR__ . '/config.php';
  class API {
    function Select() {
        $db = new Connect;
        $users = array();
        $data = $db->prepare('SELECT * FROM users');
        $data->execute();
        while($OutputData = $data->fetch(PDO::FETCH_ASSOC)) {
            // $users[$OutputData['username']] = array(
            $users[] = array(
                'username' => $OutputData['username'],
                'fullname' => $OutputData['fullname'],
                'email' => $OutputData['email']
            );
        }

        return json_encode($users);
    }
  }

  $API = new API;
  header('Content-Type: application/json');
  echo $API->Select();
?>

我做错了什么,我该如何解决?

【问题讨论】:

  • 你有一个数组,你的循环试图回显一个数组。在其中添加另一个循环,这样您就可以遍历子数组的键/值
  • @aynber - 我不明白。我跟着教程。
  • $decoded 是一个用户数组。如果您在该循环内var_dump($val);,您会看到$val 是包含单个用户的数组。您需要添加另一个循环才能进入用户数组。

标签: php api curl


【解决方案1】:

使用 aynber 的建议,我能够通过将 foreach 循环更新为如下所示来解决问题:

foreach($decoded as $key => $val) {
  foreach($val as $key2 => $val2) {
    echo $key2 . ': ' . $val2 . '<br>';
  }
}

【讨论】:

    猜你喜欢
    • 2015-11-21
    • 2013-07-03
    • 2014-11-21
    相关资源
    最近更新 更多