4

I am using Twilio's PHP SDK to send SMS. Below is the code:

<?php
// Required if your environment does not handle autoloading
require './autoload.php';

// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$sid = 'XXXXXXXXXXXXXXXXXXXXXXXX';
$token = 'XXXXXXXXXXXXXXXXXXXX';
$client = new Client($sid, $token);

// Use the client to do fun stuff like send text messages!
$client->messages->create(
    // the number you'd like to send the message to
    '+XXXXXXXXXX',
    array(
        // A Twilio phone number you purchased at twilio.com/console
        'from' => '+XXXXXXXX',
        // the body of the text message you'd like to send
        'body' => 'Hey Jenny! Good luck on the bar exam!'
    )
);

**Response:
[Twilio.Api.V2010.MessageInstance accountSid=XXXXXXXXXXXXXXXX sid=XXXXXXXXXXXXXXX]**

How I can get the response in JSON Format? Any help is appreciated.

Vijay
  • 246
  • 1
  • 6
  • anyone please.. – Vijay Apr 19 '17 at 05:21
  • You can construct the API call yourself to get the JSON response. Can I ask why you need the JSON and why the object the helper library doesn't give you what you need? – philnash Apr 19 '17 at 07:56
  • From Twilio documentation: "Json: If your function returns valid Json, you should be able to access it via widgets.MY_WIDGET_NAME.parsed" – Michael Niño May 12 '18 at 14:20

2 Answers2

2

I'm not sure if I have understood your intent properly, however, I've created a new GitHub repository which I hope gives you the information that you're after, if you're still interested.

The MessageInstance object which the call to $client->messages->create() returns won't return anything of value when passed to json_encode(). This is because the relevant properties are contained in a protected property, so json_encode() cannot access them.

One option to get around this is to use a class which implements JsonSerializable and returns a JSON representation of a MessageInstance object, such as JsonMessageInstance.

Have a look at the code and let me know if this does what you wanted.

Matthew Setter
  • 2,397
  • 1
  • 19
  • 18
0

The quick answer is:

$json_string = json_encode(</POST|GET>);

Use the $_POST or $_GET super globals and you get a json string format.

e.g.

/*
 * Imagine this is the POST request
 *
 * $_POST = [
 *     'foo' => 'Hello',
 *     'bar' => 'World!'
 * ];
 *
 */


$json_string = json_encode($_POST); // You get → {"foo":"Hello","bar":"World!"}

In this way you encode the values in a JSON representation.

AyaxDev
  • 9
  • 2