user2273278
user2273278

Reputation: 1315

Display usernames from JSON response

i'm trying to display a list of all the Usernames from this JSON response through the enjin API but i am getting this error:

Warning: Invalid argument supplied for foreach()

Code

<?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>

Any help is appreciated. thanks

Upvotes: 1

Views: 333

Answers (1)

Jon
Jon

Reputation: 4736

You don't set it up so it goes in to the variable, but rather gets sent to the output stream.

Add:

curl_setopt($s, CURLOPT_RETURNTRANSFER, 1);

Before you call curl_exec() so that it gets put in to your variable. See curl_setopt for CURLOPT_RETURNTRANSFER:

TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

Full code that works:

<?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>

Upvotes: 1

Related Questions