0

I am trying to get specific data from Twilio's Phone Validator curl command:

$cmd='curl -XGET "https://lookups.twilio.com/v1/PhoneNumbers/5551234321'?Type=carrier&Type=caller-name" -u "{AccountSid}:{AuthToken}" ';
exec($cmd,$result);

When I print_r the result, I get an array.

echo '<pre>'; print_r($result); '</pre>';

Array
(
[0] => {"caller_name": {"caller_name": "JOHN SMITH", "caller_type": "CONSUMER", "error_code": null}, "country_code": "US", "phone_number": "+5551234321", "national_format": "(555) 123-4321", "carrier": {"mobile_country_code": "310", "mobile_network_code": "120", "name": "Sprint Spectrum, L.P.", "type": "mobile", "error_code": null}, "add_ons": null, "url": "https://lookups.twilio.com/v1/PhoneNumbers/+5551234321?Type=carrier&Type=caller-name"}
)

How can I get specific values as PHP variables? e.g. "name": "Sprint Spectrum, L.P.", "type": "mobile" as:

$name = "Sprint Spectrum, L.P."; 
$type = "mobile";

I tried:

foreach ($result->items as $item) {
   var_dump($item->carrier->name);
}

But get an error: Invalid argument supplied for foreach()

WGS
  • 199
  • 4
  • 17
  • 2
    Possible duplicate of [Get value from JSON array in PHP](http://stackoverflow.com/questions/17995877/get-value-from-json-array-in-php) – WillardSolutions Aug 16 '16 at 13:21
  • Your result is JSON encoded. You have to json_decode your $result[0], using json_decode function (see the link EatPeanutButter pasted for examples) – jquiaios Aug 16 '16 at 13:22
  • Can I recommend you try the [Twilio PHP library](https://www.twilio.com/docs/libraries/php). It handles all this for you (and makes calls without you needing to shell out to curl). – philnash Aug 16 '16 at 15:08

1 Answers1

1

Thank you @EatPeanutButter and @Julqas for your assistance. Pointed me in the right direction.

Working code:

$json = json_decode($result[0],true);

$type = $json['carrier']['type'];

$carrier = $json['carrier']['name'];
WGS
  • 199
  • 4
  • 17