Getting results from an API

I’ve never used an API before so am not sure exactly how to display the results. I’m getting them using this:

require_once('autoload.php'); 

    $MessageBird = new \MessageBird\Client('test_M9s7amT9kPp7Z92HxNzE7O8uU'); // Set your own API access key here.

    try {
    $MessageResult = $MessageBird->messages->read('49f518203543802e8b46023a68836835'); // Set a message id here
    var_dump($MessageResult);

    } catch (MessageBird\Exceptions\AuthenticateException $e) {
    // That means that your accessKey is unknown
    echo 'wrong login';

    } catch (Exception $e) {
    var_dump($e->getMessage());
    }

to get the results, the var_dump then returns this:

but I don’t know how to display the actual results. All I want is the message ([“body”]), the time it was sent ([“scheduledDatetime”]) and how many sent ([“totalSentCount”]) and how many were successful ([“totalDeliveredCount”])

Looks like the API is returning an object, so to access a property such as the body, just do:

$MessageResult->body;

Brilliant thank you, that worked but how do I get the results from some of the other variables? I tried the following but they didn’t work

b>Date sent:</b> <?php echo $MessageResult->statusDatetime; ?>&nbsp;&nbsp; <b>Sent:</b> <?php echo $MessageResult->totalSentCount; ?>&nbsp;&nbsp; <b>Delivered:</b> <?php echo $MessageResult->totalDeliveredCount; ?>&nbsp;&nbsp; <b>Undelivered:</b> <?php echo $MessageResult->totalDeliveryFailedCount; ?>
Also if I wanted to list things from an API (like the one below) how would I do that?

require_once('autoload.php'); 

    $MessageBird = new \MessageBird\Client('test_M9s7amT9kPp7Z92HxNzE7O8uU'); // Set your own API access key here.

try {
    $MessageList = $MessageBird->messages->getList(array ('offset' => 100, 'count' => 30));
    var_dump($MessageList);

} catch (MessageBird\Exceptions\AuthenticateException $e) {
    // That means that your accessKey is unknown
    echo 'wrong login';

} catch (Exception $e) {
    var_dump($e->getMessage());
}

The results are:

Again I want to get the body text, send date etc for each of the messages sent.

If you look at the var_dump of the results, you can see the object has a property called items which is an array, so you can just use a foreach loop to go through each message and echo out the details you want.

Your query above hasn’t returned any messages though, which seems to be because you’ve used an offset of 100 and there are only 2 messages in total on the system.

The MessageBird API documentation is useful here, as it shows an example response when trying to read a message:

{
  'id' => 'e60a6f90453a19019c56ed6b20170831',
  'href' => 'https://rest.messagebird.com/messages/e60a6f90453a19019c56ed6b20170831',
  'direction' => 'mt',
  'type' => 'sms',
  'originator' => 'MessageBird',
  'body' => 'This is a test message.',
  'reference' => NULL,
  'validity' => NULL,
  'gateway' => 240,
  'typeDetails' => {},
  'datacoding' => 'plain',
  'mclass' => 1,
  'scheduledDatetime' => NULL,
  'createdDatetime' => '2014-10-23T12:17:33+00:00',
  'recipients' => array(
    'totalCount' => 1,
    'totalSentCount' => 1,
    'totalDeliveredCount' => 0,
    'totalDeliveryFailedCount' => 0,
    'items' => array (
      {
        'recipient' => 31612345678,
        'status' => 'delivered',
        'statusDatetime' => '2014-10-23T12:17:33+00:00',
      },
    )
  )
}

You can see that the properties you’re trying to access are nested inside arrays. To access the totalSentCount (in the case of there only being a single recipient) you’d do something like this:

echo $MessageResult->recipients[0]->totalSentCount;

if the message has multiple recipients, then you’ll have to loop over the recipients array.

Thank you, I’ll try that

So I need to add ‘->recipients[0]’ before each property to get it to show the results?

EDIT: I tried that but got an error: PHP Fatal error: Cannot use object of type stdClass as array

I tried this: <b>Sent:</b> <?php echo $MessageResult->recipients[0]->totalSentCount; ?>

I tried using a foreach loop but thing I’ve got something wrong as nothing was returned (although the var_dump did return results).

I tried this:

<?php 
foreach ($MessageResult->body as $sms_body) {
    echo $sms_body; } ?>

Hmm, OK, I’ve just looked back at your original var_dump output and the recipients property is indeed an object rather than an array, which is at odds with what the docs say… in any case, that means you’ll need to do this:

echo $MessageResult->recipients->totalSentCount;

The body property is a string, not an array, so you can’t loop over it like that. What I was talking about was using foreach to loop over the $MessageList results:

$MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'count' => 30));

if ($MessageList->count > 0) {
    foreach ($MessageList->items as $message) {
        echo $Message->body;
        // etc
    }
}

Thanks that works perfectly :smile:
Although the time sent still isn’t working, I tried using echo $MessageResult->recipients->items->statusDatetime; but that showed nothing

Okay I changed it to <?php echo $MessageResult->recipients->items[0]->statusDatetime; ? to get the time it was sent but it’s displaying it as 2014-10-22T15:56:45+00:00 which is guess it obvious but is there a way I can display it as DD/MM/YYYY Hour:Minute?

Take a look at PHP’s DateTime class, it’ll let you output a date/time value in any format you want.

I tried changing it to <?php echo $MessageResult->recipients->items[0]->statusDatetime->format( 'd-m-Y' ); ?> but that didn’t display anything

statusDatetime is just a string, you’ll have to create a DateTime object from it first:

$date = new DateTime($MessageResult->recipients->items[0]->statusDatetime);
echo $date->format( 'd-m-Y' );

I still can’t seem to get this to work :frowning:

Thank you the date/time is now displaying exactly right

I’ve tried to do that but it didn’t return anything at all :frowning:

Sorry to ask a stupid question, but just to check: you’re combining the code I gave you with the rest of your example code (i.e. requiring the autoloader, creating the client object etc) right?

Yep I’ve got the autoload.php file and all of that stuff in the header

[code] require_once(‘autoload.php’);

$MessageBird = new \MessageBird\Client('test_M9s7amT9kPp7Z92HxNzE7O8uU'); // Set your own API access key here.

try {
$MessageList = $MessageBird->messages->getList(array (‘count’ => 30));
var_dump($MessageList);

} catch (MessageBird\Exceptions\AuthenticateException $e) {
// That means that your accessKey is unknown
echo ‘wrong login’;

} catch (Exception $e) {
var_dump($e->getMessage());
}[/code]

And then in the body I’ve got this:

<div class="list-column">
                  <b>Message:</b>  <?php 
if ($MessageList->count > 0) {
    foreach ($MessageList->items as $message) {
        echo $Message->body;
        // etc
    }
}  ?>
            </div>