【问题标题】:Display usernames from JSON response显示来自 JSON 响应的用户名
【发布时间】:2013-04-14 00:59:31
【问题描述】:

我正在尝试通过 enjin API 显示此 JSON 响应中的所有用户名列表,但我收到此错误:

警告:为 foreach() 提供的参数无效

代码

<?php

$s = curl_init();
curl_setopt($s, CURLOPT_URL, 'http://oceanix.enjin.com/api/get-users');

$output = curl_exec($s);
curl_close($s);

$decodedJson = json_decode($output);
?>

<table>
    <tr>
        <th>username</th>
    </tr>
<?php

    foreach ($decodedJson as $username) { ?>
    <tr>
        <td><?php echo $username->username; ?></td>
    </tr>
<?php 
}?>
</table>

感谢任何帮助。谢谢

【问题讨论】:

  • 请在此处不解码打印 $output。
  • "340341:{"username":"Nord","forum_post_count":"0","forum_votes":"0","forum_up_votes":"0","forum_down_votes":"0 ","lastseen":"1357188​​768","datejoined":"1357188​​768"},
  • 这看起来不像是有效的 JSON。您能否将整个输出复制并粘贴到问题body 中?你能用var_dump()之类的东西发布$decodedJson的内容吗?
  • 在解码之前用 { 和 } 包围您的输入 JSON。另外,var_dump( $decodedJson )——它可能是 NULL。
  • @J.D.Pace JSON 已经被正确包围了......

标签: php json api curl


【解决方案1】:

你没有设置它,所以它进入变量,而是被发送到输出流。

添加:

curl_setopt($s, CURLOPT_RETURNTRANSFER, 1);

在您调用curl_exec() 之前,它会被放入您的变量中。 CURLOPT_RETURNTRANSFERcurl_setopt

TRUE 将传输作为 curl_exec() 的返回值的字符串返回,而不是直接输出。

有效的完整代码:

<?php

$s = curl_init();
curl_setopt($s, CURLOPT_URL, 'http://oceanix.enjin.com/api/get-users');
curl_setopt($s, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($s);
curl_close($s);

$decodedJson = json_decode($output);
?>

<table>
    <tr>
        <th>username</th>
    </tr>
<?php

    foreach ($decodedJson as $username) { ?>
    <tr>
        <td><?php echo $username->username; ?></td>
    </tr>
<?php 
}?>
</table>

【讨论】:

  • 谢谢。它现在不显示响应,但即使没有按照@imsiso 的建议进行解码,我仍然收到此错误“警告:foreach() 提供的参数无效”。
  • @user2273278 我编辑了用于测试它的完整代码,它按预期输出。
  • @user2273278 没问题^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
相关资源
最近更新 更多