【问题标题】:Object of class stdClass could not be converted to string with Halo API无法使用 Halo API 将类 stdClass 的对象转换为字符串
【发布时间】:2016-02-03 23:08:18
【问题描述】:

所以我有以下代码:

    <?PHP

    $remote_url = 'https://www.haloapi.com/stats/h5/players/PLAYER/matches';

    // Create a stream
    $opts = array(
      'http'=>array(
        'method'=>"GET",
        'header' => "Ocp-Apim-Subscription-Key: MY SUBSCRIPTION KEY")                 
      );

    $context = stream_context_create($opts);

    // Open the file using the HTTP headers set above
    $file = file_get_contents($remote_url, false, $context);

    print(json_decode($file));

    ?>

它给了我以下错误:

可捕获的致命错误:第 17 行的 C:\xampp\htdocs\HaloAPItest\index.php 中的类 stdClass 的对象无法转换为字符串

我该怎么办?

【问题讨论】:

  • 您在寻找print_r(),而不是print()

标签: php


【解决方案1】:

达伦在他的评论中说了什么。 print_r 处理任何类的变量。只打印字符串。

另一个有用的函数是 var_dump。像 var_dump_pre 一样写一个函数来做它也很好 &lt;pre&gt; &lt;/pre&gt; 输出周围的标签。这在屏幕上很好地格式化了它。

【讨论】:

  • 谢谢,所以如果我只使用 echo 或 print 应该可以吗?我用了var_dump,它说是字符串,然后还是打印出了loooong字符串
  • @ImInThatCorner 正确,如果它是字符串打印将起作用。如果它不是字符串,则打印和回显将出错或仅打印出类型。使用 var_dump 或至少使用 print_r 总是更有益,因此您可以打印任何对象而不必担心类型。您还需要检查 file_get_contents 函数是否返回成功值而不是失败结果 file_get_contents:"该函数返回读取数据或失败时返回 FALSE。"
猜你喜欢
  • 2016-05-13
  • 2011-04-06
  • 2018-10-19
  • 2020-03-16
  • 2021-11-10
  • 2014-06-12
相关资源
最近更新 更多