Search code examples
phpjsonmessagebird

Converting PHP var_dump array to JSON


been looking for a solution. Couldn't find one so my last resort is of course here.

I am using an API from MessageBird. The intention of the code is to spit out a message list.

My Code:

require_once(__DIR__ . '/messagebird/vendor/autoload.php');
$MessageBird = new \MessageBird\Client('XXXXX'); // Set your own API access key here.
try {
$MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'limit' => 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());
}

$json = json_decode($MessageList, true);

foreach($json as $item) {
  echo $item['body'];
}

This is the data "var_dump" outputs:

object(MessageBird\Objects\BaseList)#147 (6) {
  ["limit"]=>
  int(30)
  ["offset"]=>
  int(0)
  ["count"]=>
    int(24)
  ["totalCount"]=>
  int(24)
  ["links"]=>
  object(stdClass)#48 (4) {
    ["first"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
    ["previous"]=>
    NULL
    ["next"]=>
    NULL
    ["last"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
  }
  ["items"]=>
  array(24) {
    [0]=>
    object(MessageBird\Objects\Message)#148 (16) {
      ["id":protected]=>
      string(32) "XXX"
      ["href":protected]=>
      string(70) 
"https://rest.messagebird.com/messages/XXX"
      ["direction"]=>
      string(2) "mt"
      ["type"]=>
      string(3) "sms"
      ["originator"]=>
      string(5) "Test Sender"
      ["body"]=>
      string(416) "Hey Blah Blah Test Message."
      ["reference"]=>

I am unsure how to go about being able to convert the data to JSON so I can use foreach code to separate the records.


Solution

  • I am unsure how to go about being able to convert the data to JSON so I can use foreach code to separate the records.

    I think there is a fairly serious misunderstanding here. If you want to foreach over some data, you don't need var_dump or JSON, let alone both - you just need the data.

    var_dump is a function for displaying structures to the programmer during debugging; it's not intended to be reversible, or ever used in production code.

    JSON is a serialization format for representing data as text so you can transmit it from one program to another. You're not transmitting your object anywhere, so you don't need JSON.

    What you want is this:

    try
    {
        $MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'limit' => 30));
        foreach($MessageList->items as $item) {
          echo $item->body;
        }
    }
    // Your exception handling here - note that you can't do anything with `$MessageList` if an exception happened; it won't exist.